Doing something before program exit Doing something before program exit python python

Doing something before program exit


Check out the atexit module:

http://docs.python.org/library/atexit.html

For example, if I wanted to print a message when my application was terminating:

import atexitdef exit_handler():    print 'My application is ending!'atexit.register(exit_handler)

Just be aware that this works great for normal termination of the script, but it won't get called in all cases (e.g. fatal internal errors).


If you want something to always run, even on errors, use try: finally: like this -

def main():    try:        execute_app()    finally:        handle_cleanup()if __name__=='__main__':    main()

If you want to also handle exceptions you can insert an except: before the finally:


If you stop the script by raising a KeyboardInterrupt (e.g. by pressing Ctrl-C), you can catch that just as a standard exception. You can also catch SystemExit in the same way.

try:    ...except KeyboardInterrupt:    # clean up    raise

I mention this just so that you know about it; the 'right' way to do this is the atexit module mentioned above.