well, from the title, it seems to be what you want to do is have something executed when the program is shutting down
If so, you could make a function and then assign all exiting to it (KeyboardInterrupt (Ctrl-C, etc), etc)

Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.

register( func[, *args[, **kargs]])

Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register().
At normal program termination (for instance, if sys.exit() is called or the main module's execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later.