Issue #5262: Improved fix.
[python.git] / Doc / library / atexit.rst
blob8b33d5c91f4d362df78bbb402b47a944abb88d21
2 :mod:`atexit` --- Exit handlers
3 ===============================
5 .. module:: atexit
6    :synopsis: Register and execute cleanup functions.
7 .. moduleauthor:: Skip Montanaro <skip@pobox.com>
8 .. sectionauthor:: Skip Montanaro <skip@pobox.com>
11 .. versionadded:: 2.0
13 The :mod:`atexit` module defines a single function to register cleanup
14 functions.  Functions thus registered are automatically executed upon normal
15 interpreter termination.
17 Note: the functions registered via this module are not called when the program
18 is killed by a signal, when a Python fatal internal error is detected, or when
19 :func:`os._exit` is called.
21 .. index:: single: exitfunc (in sys)
23 This is an alternate interface to the functionality provided by the
24 ``sys.exitfunc`` variable.
26 Note: This module is unlikely to work correctly when used with other code that
27 sets ``sys.exitfunc``.  In particular, other core Python modules are free to use
28 :mod:`atexit` without the programmer's knowledge.  Authors who use
29 ``sys.exitfunc`` should convert their code to use :mod:`atexit` instead.  The
30 simplest way to convert code that sets ``sys.exitfunc`` is to import
31 :mod:`atexit` and register the function that had been bound to ``sys.exitfunc``.
34 .. function:: register(func[, *args[, **kargs]])
36    Register *func* as a function to be executed at termination.  Any optional
37    arguments that are to be passed to *func* must be passed as arguments to
38    :func:`register`.
40    At normal program termination (for instance, if :func:`sys.exit` is called or
41    the main module's execution completes), all functions registered are called in
42    last in, first out order.  The assumption is that lower level modules will
43    normally be imported before higher level modules and thus must be cleaned up
44    later.
46    If an exception is raised during execution of the exit handlers, a traceback is
47    printed (unless :exc:`SystemExit` is raised) and the exception information is
48    saved.  After all exit handlers have had a chance to run the last exception to
49    be raised is re-raised.
51    .. versionchanged:: 2.6
52       This function now returns *func* which makes it possible to use it as a
53       decorator without binding the original name to ``None``.
56 .. seealso::
58    Module :mod:`readline`
59       Useful example of :mod:`atexit` to read and write :mod:`readline` history files.
62 .. _atexit-example:
64 :mod:`atexit` Example
65 ---------------------
67 The following simple example demonstrates how a module can initialize a counter
68 from a file when it is imported and save the counter's updated value
69 automatically when the program terminates without relying on the application
70 making an explicit call into this module at termination. ::
72    try:
73        _count = int(open("/tmp/counter").read())
74    except IOError:
75        _count = 0
77    def incrcounter(n):
78        global _count
79        _count = _count + n
81    def savecounter():
82        open("/tmp/counter", "w").write("%d" % _count)
84    import atexit
85    atexit.register(savecounter)
87 Positional and keyword arguments may also be passed to :func:`register` to be
88 passed along to the registered function when it is called::
90    def goodbye(name, adjective):
91        print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)
93    import atexit
94    atexit.register(goodbye, 'Donny', 'nice')
96    # or:
97    atexit.register(goodbye, adjective='nice', name='Donny')
99 Usage as a :term:`decorator`::
101    import atexit
103    @atexit.register
104    def goodbye():
105        print "You are now leaving the Python sector."
107 This obviously only works with functions that don't take arguments.