Doing anything before exiting a program

How do you have a function or something that will be executed before the release of your program? I have a script that will constantly work in the background, and I need to save it some data to a file before it is released. Is there a standard way to do this?

+47
function python exit
Oct 03 2018-10-10
source share
3 answers

Check the atexit module:

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

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

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

Just keep in mind that this works fine for a normal script termination, but it will not be called in all cases (e.g. fatal internal errors).

+70
03 Oct 2018-10-10 at
source share

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

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

If you want to handle exceptions as well, you can insert with the exception of: until the final:

+14
Oct 03 2018-10-10 at
source share

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

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

I mention it just so that you know about it; The "right" way is the atexit module mentioned above.

+5
Oct 03 '10 at 15:11
source share



All Articles