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.3k times
11
-
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
24
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()

ideasman42
- 42,413
- 44
- 197
- 320

miku
- 181,842
- 47
- 306
- 310
-
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
9
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
- 54,681
- 14
- 94
- 131
3
Use the KeyboardInterrupt exception and call your function in the except
block.

ig0774
- 39,669
- 3
- 55
- 57