Is there anyway I can make my script execute one of my functions when Ctrl+c is hit when the script is running?
Asked
Active
Viewed 1.2k times
10
-
See http://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except for several options. – DSM Aug 09 '11 at 01:30
3 Answers
23
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()
miku
- 172,072
- 46
- 300
- 307
-
note: this one should also hit the signal handler when you go `kill -2 [pid]` in the OS – wim Aug 09 '11 at 02:45
-
@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? – miku Aug 09 '11 at 02:56
-
1I 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. – wim Aug 09 '11 at 02:58
8
Sure.
try:
# Your normal block of code
except KeyboardInterrupt:
# Your code which is executed when CTRL+C is pressed.
finally:
# Your code which is always executed.
Senthil Kumaran
- 51,269
- 14
- 86
- 124
3
Use the KeyboardInterrupt exception and call your function in the except block.
ig0774
- 36,969
- 3
- 54
- 56