Gracefully exiting CLI application

Nobody nobody at nowhere.com
Tue Jul 28 09:31:56 EDT 2009


On Mon, 27 Jul 2009 22:35:01 +0200, David wrote:

> I am writing a command line application, and I need to perform some
> cleaning on exit even if the process is killed. How can I do that with
> python?

Killed by what means?

Ctrl-C sends SIGINT which is converted to a KeyboardInterrupt exception.
This can be caught, or if it's allowed to terminate the process, any exit
handlers registered via atexit.register() will be used.

For other signals, you can install a handler with signal.signal(). This
can call sys.exit() or raise an exception (e.g. KeyboardInterrupt).

OTOH, if the process is terminated by SIGKILL, there's nothing you can do
about it. And although it's possible to trap SIGSEGV, you shouldn't assume
that the Python interpreter is still functional at this point.




More information about the Python-list mailing list