blob: 1d84d4587fd9c009c4eb207fac24476609897666 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Christian Heimes895627f2007-12-08 17:28:33 +00007.. moduleauthor:: Skip Montanaro <skip@pobox.com>
8.. sectionauthor:: Skip Montanaro <skip@pobox.com>
Georg Brandl116aa622007-08-15 14:28:22 +00009
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040010--------------
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`atexit` module defines functions to register and unregister cleanup
13functions. Functions thus registered are automatically executed upon normal
Larry Hastings11917092012-07-14 18:20:37 -070014interpreter termination. :mod:`atexit` runs these functions in the *reverse*
15order in which they were registered; if you register ``A``, ``B``, and ``C``,
16at interpreter termination time they will be run in the order ``C``, ``B``,
17``A``.
Georg Brandl116aa622007-08-15 14:28:22 +000018
Larry Hastings11917092012-07-14 18:20:37 -070019**Note:** The functions registered via this module are not called when the
20program is killed by a signal not handled by Python, when a Python fatal
21internal error is detected, or when :func:`os._exit` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000022
23
Georg Brandlb868a662009-04-02 02:56:10 +000024.. function:: register(func, *args, **kargs)
Georg Brandl116aa622007-08-15 14:28:22 +000025
26 Register *func* as a function to be executed at termination. Any optional
27 arguments that are to be passed to *func* must be passed as arguments to
Éric Araujoccddc472012-02-15 17:07:49 +010028 :func:`register`. It is possible to register the same function and arguments
29 more than once.
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 At normal program termination (for instance, if :func:`sys.exit` is called or
32 the main module's execution completes), all functions registered are called in
33 last in, first out order. The assumption is that lower level modules will
34 normally be imported before higher level modules and thus must be cleaned up
35 later.
36
37 If an exception is raised during execution of the exit handlers, a traceback is
38 printed (unless :exc:`SystemExit` is raised) and the exception information is
39 saved. After all exit handlers have had a chance to run the last exception to
40 be raised is re-raised.
41
Éric Araujoccddc472012-02-15 17:07:49 +010042 This function returns *func*, which makes it possible to use it as a
43 decorator.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45
46.. function:: unregister(func)
47
Éric Araujoccddc472012-02-15 17:07:49 +010048 Remove *func* from the list of functions to be run at interpreter
Georg Brandl116aa622007-08-15 14:28:22 +000049 shutdown. After calling :func:`unregister`, *func* is guaranteed not to be
Éric Araujoccddc472012-02-15 17:07:49 +010050 called when the interpreter shuts down, even if it was registered more than
51 once. :func:`unregister` silently does nothing if *func* was not previously
52 registered.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Georg Brandl116aa622007-08-15 14:28:22 +000054
55.. seealso::
56
57 Module :mod:`readline`
Georg Brandlb868a662009-04-02 02:56:10 +000058 Useful example of :mod:`atexit` to read and write :mod:`readline` history
59 files.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
62.. _atexit-example:
63
64:mod:`atexit` Example
65---------------------
66
67The following simple example demonstrates how a module can initialize a counter
68from a file when it is imported and save the counter's updated value
69automatically when the program terminates without relying on the application
70making an explicit call into this module at termination. ::
71
72 try:
Petri Lehtinen3c75a482013-02-23 19:34:15 +010073 with open("counterfile") as infile:
Éric Araujoe4f6a802011-03-12 15:56:09 +010074 _count = int(infile.read())
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020075 except FileNotFoundError:
Georg Brandl116aa622007-08-15 14:28:22 +000076 _count = 0
77
78 def incrcounter(n):
79 global _count
80 _count = _count + n
81
82 def savecounter():
Petri Lehtinen3c75a482013-02-23 19:34:15 +010083 with open("counterfile", "w") as outfile:
Éric Araujoa3dd56b2011-03-11 17:42:48 +010084 outfile.write("%d" % _count)
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 import atexit
87 atexit.register(savecounter)
88
89Positional and keyword arguments may also be passed to :func:`register` to be
90passed along to the registered function when it is called::
91
92 def goodbye(name, adjective):
Georg Brandl6911e3c2007-09-04 07:15:32 +000093 print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 import atexit
96 atexit.register(goodbye, 'Donny', 'nice')
97
98 # or:
99 atexit.register(goodbye, adjective='nice', name='Donny')
100
Christian Heimesd8654cf2007-12-02 15:22:16 +0000101Usage as a :term:`decorator`::
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 import atexit
104
105 @atexit.register
106 def goodbye():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000107 print("You are now leaving the Python sector.")
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Éric Araujoccddc472012-02-15 17:07:49 +0100109This only works with functions that can be called without arguments.