I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup.
In Perl I'd do this:
$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
How do I do the analogue of this in Python?
You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the
signal.signal(signalnum, handler)
function is used to register thehandler
function for signalsignalnum
.You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:
You can handle CTRL+C by catching the
KeyboardInterrupt
exception. You can implement any clean-up code in the exception handler.From Python's documentation: