Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing something before program exit

People also ask

How does Python handle exit?

Exit Programs With the quit() Function in Python This site module contains the quit() function,, which can be used to exit the program within an interpreter. The quit() function raises a SystemExit exception when executed; thus, this process exits our program.

How do you break a program execution?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution.

How do you end a program after else?

Just, return something, and if that is returned, then let your main function exit, either by falling off the end, by using a return statement, or calling sys. exit() / raise SystemExit . This also reads pretty naturally ("while keep going do your code").

How do you exit a Python program quickly?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.


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 atexit

def 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.