Is there anyway I can make my script execute one of my functions when Ctrl+c is hit when the script is running?
3 Answers
Take a look at signal handlers. CTRL-C corresponds to SIGINT (signal #2 on posix systems).
Example:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
print("You pressed Ctrl+C - or killed me with -2")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C")
signal.pause()
3 Comments
wim
note: this one should also hit the signal handler when you go
kill -2 [pid] in the OSmiku
@wim, good point, thanks, added a hint to my answer - is there actually a way to distinguish a kill by keyboard from a kill by kill?
wim
I have seen the former will raise a
KeyboardInterrupt exception in python, the latter won't. But I'm not sure on the implementation details of why this is so.