I want to catch KeyboardInterrupt
globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this?
63
votes
5 Answers
137
votes
26
votes
16
votes
You can also use signal like this:
import signal, time
def handler(signum, frame):
print 'I just clicked on CTRL-C '
signal.signal(signal.SIGINT, handler)
print "waiting for 10 s"
time.sleep(10)
Output:
waiting for 10 s
^CI just clicked on CTRL-C
N.B: Don't mix the use of signal with threads.
10
votes
1
votes
There's no other way to do this, apart from encasing your entire script in a main()
function and surrounding that with a try..except
block - which is pretty much the same:
def main():
# Your script goes here
pass
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
# cleanup code here
pass