I want to know if it's possible to catch a Control-C in python in the following manner:
if input != contr-c: #DO THINGS else: #quit
I've read up on stuff with try
and except KeyboardInterrupt
but they're not working for me.
You can handle CTRL + C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.
Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can't be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.
Roughly speaking the Ctrl + Z from a Unix/Linux terminal in cooked or canonical modes will cause the terminal driver to generate a "suspend" signal to the foreground application. So you have two different overall approaches. Change the terminal settings or ignore the signal.
When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.
Consider reading this page about handling exceptions.. It should help.
As @abarnert has said, do sys.exit()
after except KeyboardInterrupt:
.
Something like
try: # DO THINGS except KeyboardInterrupt: # quit sys.exit()
You can also use the built in exit()
function, but as @eryksun pointed out, sys.exit
is more reliable.
From your comments, it sounds like your only problem with except KeyboardInterrupt:
is that you don't know how to make it exit when you get that interrupt.
If so, that's simple:
import sys try: user_input = input() except KeyboardInterrupt: sys.exit(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With