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?
And as a context manager:
To use:
Nested handlers:
From here: https://gist.github.com/2907502
In contrast to Matt J his answer, I use a simple object. This gives me the possibily to parse this handler to all the threads that needs to be stopped securlery.
Elsewhere
Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.
Setting a signal handler behaves the same.
On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.
Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)
Yet Another Snippet
Referred
main
as the main function andexit_gracefully
as the CTRL + c handlerI adapted the code from @udi to support multiple signals (nothing fancy) :
This code support the keyboard interrupt call (
SIGINT
) and theSIGTERM
(kill <process>
)Register your handler with
signal.signal
like this:Code adapted from here.
More documentation on
signal
can be found here.