Fix Python – Doing something before program exit

Question

Asked By – RacecaR

How can you have a function or something that will be executed before your program quits? I have a script that will be constantly running in the background, and I need it to save some data to a file before it exits. Is there a standard way of doing this?

Now we will see solution for issue: Doing something before program exit


Answer

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

This question is answered By – Brent Writes Code

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0