The atexit Module

(2.0 only) The atexit module allows you to register one or more functions that are called when the interpreter is terminated.

To register a function, simply call the register function, as shown in Example 1-78. You can also add one or more extra arguments, which are passed as arguments to the exit function.

Example 1-78. Using the atexit Module

File: atexit-example-1.py

import atexit

def exit(*args):
    print "exit", args

# register two exit handler
atexit.register(exit)
atexit.register(exit, 1)
atexit.register(exit, "hello", "world")

exit ('hello', 'world')
exit (1,)
exit ()

This module is a straightforward wrapper for the sys.exitfunc hook.

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.