When i press CTRL+C to cancel a running python script, is there a way to run a certain python code before the script terminates?
-
1You can catch the `KeyboardInterrupt` error; or you can set up [a signal handler](http://stackoverflow.com/a/1112350/344643); or you can do something at exit time [using the atexit module](http://docs.python.org/2/library/atexit.html#atexit-example). – Waleed Khan Dec 08 '13 at 21:54
5 Answers
Use try/except
to capture for KeyboardInterrupt
, which is raised when you press CTRL+C.
Here is a basic script to demonstrate:
try:
# Main code
while True:
print 'hi!'
except KeyboardInterrupt:
# Cleanup/exiting code
print 'done!'
This will continually print 'hi!'
until you press CTRL+C. Then, it prints 'done!'
and exits.
CTRL+C raises KeyboardInterrupt
. You can catch it just like any other exception:
try:
main()
except KeyboardInterrupt:
cleanup()
If you really don't like that, you can also use atexit.register
to register cleanup actions to run (provided that you don't do something really nasty and cause the interpreter to exit in a funky way)

- 300,191
- 65
- 633
- 696
This code
import time
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
print "Any clean"
gives
deck@crunch ~/tmp $ python test.py
^CAny clean
when I press Ctrl+C
when executing.
You just have to handle KeyboardInterrupt exception.
Also you can deal with signals to set handlers.

- 1,969
- 4
- 20
- 41
I'm pretty sure you just need a try/finally
block.
Try out this script:
import time
def main():
try:
while True:
print("blah blah")
time.sleep(5)
except KeyboardInterrupt:
print("caught CTRL-C")
finally:
print("do cleanup")
if __name__ == '__main__':
main()
Output should be something like:
blah blah
caught CTRL-C
do cleanup

- 353
- 1
- 7