blob: fd884d72bb1d6ad5e2b4deb7d887f1fc6dd0531c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`atexit` --- Exit handlers
3===============================
4
5.. module:: atexit
6 :synopsis: Register and execute cleanup functions.
Skip Montanaro54662462007-12-08 15:26:16 +00007.. moduleauthor:: Skip Montanaro <skip@pobox.com>
8.. sectionauthor:: Skip Montanaro <skip@pobox.com>
Georg Brandl8ec7f652007-08-15 14:28:01 +00009
10
11.. versionadded:: 2.0
12
13The :mod:`atexit` module defines a single function to register cleanup
14functions. Functions thus registered are automatically executed upon normal
Éric Araujo43162e22011-07-29 18:04:24 +020015interpreter termination. The order in which the functions are called is not
16defined; if you have cleanup operations that depend on each other, you should
17wrap them in a function and register that one. This keeps :mod:`atexit` simple.
Georg Brandl8ec7f652007-08-15 14:28:01 +000018
Raymond Hettingere0e08222010-11-06 07:10:31 +000019.. seealso::
20
21 Latest version of the `atexit Python source code
22 <http://svn.python.org/view/python/branches/release27-maint/Lib/atexit.py?view=markup>`_
23
Georg Brandl8ec7f652007-08-15 14:28:01 +000024Note: the functions registered via this module are not called when the program
Georg Brandl420cca92010-11-26 07:21:01 +000025is killed by a signal not handled by Python, when a Python fatal internal error
26is detected, or when :func:`os._exit` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28.. index:: single: exitfunc (in sys)
29
30This is an alternate interface to the functionality provided by the
31``sys.exitfunc`` variable.
32
33Note: This module is unlikely to work correctly when used with other code that
34sets ``sys.exitfunc``. In particular, other core Python modules are free to use
35:mod:`atexit` without the programmer's knowledge. Authors who use
36``sys.exitfunc`` should convert their code to use :mod:`atexit` instead. The
37simplest way to convert code that sets ``sys.exitfunc`` is to import
38:mod:`atexit` and register the function that had been bound to ``sys.exitfunc``.
39
40
41.. function:: register(func[, *args[, **kargs]])
42
43 Register *func* as a function to be executed at termination. Any optional
44 arguments that are to be passed to *func* must be passed as arguments to
45 :func:`register`.
46
47 At normal program termination (for instance, if :func:`sys.exit` is called or
48 the main module's execution completes), all functions registered are called in
49 last in, first out order. The assumption is that lower level modules will
50 normally be imported before higher level modules and thus must be cleaned up
51 later.
52
53 If an exception is raised during execution of the exit handlers, a traceback is
54 printed (unless :exc:`SystemExit` is raised) and the exception information is
55 saved. After all exit handlers have had a chance to run the last exception to
56 be raised is re-raised.
57
58 .. versionchanged:: 2.6
59 This function now returns *func* which makes it possible to use it as a
60 decorator without binding the original name to ``None``.
61
62
63.. seealso::
64
65 Module :mod:`readline`
66 Useful example of :mod:`atexit` to read and write :mod:`readline` history files.
67
68
69.. _atexit-example:
70
71:mod:`atexit` Example
72---------------------
73
74The following simple example demonstrates how a module can initialize a counter
75from a file when it is imported and save the counter's updated value
76automatically when the program terminates without relying on the application
77making an explicit call into this module at termination. ::
78
79 try:
80 _count = int(open("/tmp/counter").read())
81 except IOError:
82 _count = 0
83
84 def incrcounter(n):
85 global _count
86 _count = _count + n
87
88 def savecounter():
89 open("/tmp/counter", "w").write("%d" % _count)
90
91 import atexit
92 atexit.register(savecounter)
93
94Positional and keyword arguments may also be passed to :func:`register` to be
95passed along to the registered function when it is called::
96
97 def goodbye(name, adjective):
98 print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)
99
100 import atexit
101 atexit.register(goodbye, 'Donny', 'nice')
102
103 # or:
104 atexit.register(goodbye, adjective='nice', name='Donny')
105
Georg Brandl584265b2007-12-02 14:58:50 +0000106Usage as a :term:`decorator`::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
108 import atexit
109
110 @atexit.register
111 def goodbye():
112 print "You are now leaving the Python sector."
113
114This obviously only works with functions that don't take arguments.
115