Check out the atexit module:

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

import atexit

def exit_handler():
    print 'My application is ending!'


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