blob: 0b5e121fe630cb6ea4d63d9de926db5d150faef2 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`atexit` --- Exit handlers
2===============================
3
4.. module:: atexit
5 :synopsis: Register and execute cleanup functions.
Skip Montanaro54662462007-12-08 15:26:16 +00006.. moduleauthor:: Skip Montanaro <skip@pobox.com>
7.. sectionauthor:: Skip Montanaro <skip@pobox.com>
Georg Brandl8ec7f652007-08-15 14:28:01 +00008
9
10.. versionadded:: 2.0
11
Éric Araujo29a0b572011-08-19 02:14:03 +020012**Source code:** :source:`Lib/atexit.py`
13
14--------------
15
Georg Brandl8ec7f652007-08-15 14:28:01 +000016The :mod:`atexit` module defines a single function to register cleanup
17functions. Functions thus registered are automatically executed upon normal
Charles-François Natalib817faa2013-08-21 18:25:00 +020018interpreter termination. :mod:`atexit` runs these functions in the *reverse*
19order in which they were registered; if you register ``A``, ``B``, and ``C``,
20at interpreter termination time they will be run in the order ``C``, ``B``,
21``A``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
Charles-François Natalib817faa2013-08-21 18:25:00 +020023**Note:** The functions registered via this module are not called when the
24program is killed by a signal not handled by Python, when a Python fatal
25internal error is detected, or when :func:`os._exit` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
27.. index:: single: exitfunc (in sys)
28
29This is an alternate interface to the functionality provided by the
Éric Araujod9756be2012-02-15 17:08:34 +010030:func:`sys.exitfunc` variable.
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
32Note: This module is unlikely to work correctly when used with other code that
33sets ``sys.exitfunc``. In particular, other core Python modules are free to use
34:mod:`atexit` without the programmer's knowledge. Authors who use
35``sys.exitfunc`` should convert their code to use :mod:`atexit` instead. The
36simplest way to convert code that sets ``sys.exitfunc`` is to import
37:mod:`atexit` and register the function that had been bound to ``sys.exitfunc``.
38
39
40.. function:: register(func[, *args[, **kargs]])
41
42 Register *func* as a function to be executed at termination. Any optional
43 arguments that are to be passed to *func* must be passed as arguments to
Éric Araujod9756be2012-02-15 17:08:34 +010044 :func:`register`. It is possible to register the same function and arguments
45 more than once.
Georg Brandl8ec7f652007-08-15 14:28:01 +000046
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
Éric Araujod9756be2012-02-15 17:08:34 +010059 This function now returns *func*, which makes it possible to use it as a
60 decorator.
Georg Brandl8ec7f652007-08-15 14:28:01 +000061
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:
Petri Lehtinen0b785032013-02-23 19:24:08 +010080 _count = int(open("counter").read())
Georg Brandl8ec7f652007-08-15 14:28:01 +000081 except IOError:
82 _count = 0
83
84 def incrcounter(n):
85 global _count
86 _count = _count + n
87
88 def savecounter():
Petri Lehtinen0b785032013-02-23 19:24:08 +010089 open("counter", "w").write("%d" % _count)
Georg Brandl8ec7f652007-08-15 14:28:01 +000090
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
Éric Araujod9756be2012-02-15 17:08:34 +0100114This only works with functions that can be called without arguments.