blob: dbdd81e6d01d57fbde2a286c0a2503016763222a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`atexit` --- Exit handlers
2===============================
3
4.. module:: atexit
5 :synopsis: Register and execute cleanup functions.
Christian Heimes895627f2007-12-08 17:28:33 +00006.. moduleauthor:: Skip Montanaro <skip@pobox.com>
7.. sectionauthor:: Skip Montanaro <skip@pobox.com>
Georg Brandl116aa622007-08-15 14:28:22 +00008
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The :mod:`atexit` module defines functions to register and unregister cleanup
11functions. Functions thus registered are automatically executed upon normal
Larry Hastings11917092012-07-14 18:20:37 -070012interpreter termination. :mod:`atexit` runs these functions in the *reverse*
13order in which they were registered; if you register ``A``, ``B``, and ``C``,
14at interpreter termination time they will be run in the order ``C``, ``B``,
15``A``.
Georg Brandl116aa622007-08-15 14:28:22 +000016
Larry Hastings11917092012-07-14 18:20:37 -070017**Note:** The functions registered via this module are not called when the
18program is killed by a signal not handled by Python, when a Python fatal
19internal error is detected, or when :func:`os._exit` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000020
21
Georg Brandlb868a662009-04-02 02:56:10 +000022.. function:: register(func, *args, **kargs)
Georg Brandl116aa622007-08-15 14:28:22 +000023
24 Register *func* as a function to be executed at termination. Any optional
25 arguments that are to be passed to *func* must be passed as arguments to
Éric Araujoccddc472012-02-15 17:07:49 +010026 :func:`register`. It is possible to register the same function and arguments
27 more than once.
Georg Brandl116aa622007-08-15 14:28:22 +000028
29 At normal program termination (for instance, if :func:`sys.exit` is called or
30 the main module's execution completes), all functions registered are called in
31 last in, first out order. The assumption is that lower level modules will
32 normally be imported before higher level modules and thus must be cleaned up
33 later.
34
35 If an exception is raised during execution of the exit handlers, a traceback is
36 printed (unless :exc:`SystemExit` is raised) and the exception information is
37 saved. After all exit handlers have had a chance to run the last exception to
38 be raised is re-raised.
39
Éric Araujoccddc472012-02-15 17:07:49 +010040 This function returns *func*, which makes it possible to use it as a
41 decorator.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43
44.. function:: unregister(func)
45
Éric Araujoccddc472012-02-15 17:07:49 +010046 Remove *func* from the list of functions to be run at interpreter
Georg Brandl116aa622007-08-15 14:28:22 +000047 shutdown. After calling :func:`unregister`, *func* is guaranteed not to be
Éric Araujoccddc472012-02-15 17:07:49 +010048 called when the interpreter shuts down, even if it was registered more than
49 once. :func:`unregister` silently does nothing if *func* was not previously
50 registered.
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandl116aa622007-08-15 14:28:22 +000052
53.. seealso::
54
55 Module :mod:`readline`
Georg Brandlb868a662009-04-02 02:56:10 +000056 Useful example of :mod:`atexit` to read and write :mod:`readline` history
57 files.
Georg Brandl116aa622007-08-15 14:28:22 +000058
59
60.. _atexit-example:
61
62:mod:`atexit` Example
63---------------------
64
65The following simple example demonstrates how a module can initialize a counter
66from a file when it is imported and save the counter's updated value
67automatically when the program terminates without relying on the application
68making an explicit call into this module at termination. ::
69
70 try:
Petri Lehtinen3c75a482013-02-23 19:34:15 +010071 with open("counterfile") as infile:
Éric Araujoe4f6a802011-03-12 15:56:09 +010072 _count = int(infile.read())
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020073 except FileNotFoundError:
Georg Brandl116aa622007-08-15 14:28:22 +000074 _count = 0
75
76 def incrcounter(n):
77 global _count
78 _count = _count + n
79
80 def savecounter():
Petri Lehtinen3c75a482013-02-23 19:34:15 +010081 with open("counterfile", "w") as outfile:
Éric Araujoa3dd56b2011-03-11 17:42:48 +010082 outfile.write("%d" % _count)
Georg Brandl116aa622007-08-15 14:28:22 +000083
84 import atexit
85 atexit.register(savecounter)
86
87Positional and keyword arguments may also be passed to :func:`register` to be
88passed along to the registered function when it is called::
89
90 def goodbye(name, adjective):
Georg Brandl6911e3c2007-09-04 07:15:32 +000091 print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
Georg Brandl116aa622007-08-15 14:28:22 +000092
93 import atexit
94 atexit.register(goodbye, 'Donny', 'nice')
95
96 # or:
97 atexit.register(goodbye, adjective='nice', name='Donny')
98
Christian Heimesd8654cf2007-12-02 15:22:16 +000099Usage as a :term:`decorator`::
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101 import atexit
102
103 @atexit.register
104 def goodbye():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000105 print("You are now leaving the Python sector.")
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Éric Araujoccddc472012-02-15 17:07:49 +0100107This only works with functions that can be called without arguments.