blob: 54131f5614ccabce5033ff2b66b64523121d0490 [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
Éric Araujo19f9b712011-08-19 00:49:18 +02009**Source code:** :source:`Lib/atexit.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`atexit` module defines functions to register and unregister cleanup
14functions. Functions thus registered are automatically executed upon normal
Éric Araujofe1e2982011-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 Brandl116aa622007-08-15 14:28:22 +000018
19Note: the functions registered via this module are not called when the program
Georg Brandl7c4cad52010-10-14 06:43:22 +000020is killed by a signal not handled by Python, when a Python fatal internal error
21is 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
28 :func:`register`.
29
30 At normal program termination (for instance, if :func:`sys.exit` is called or
31 the main module's execution completes), all functions registered are called in
32 last in, first out order. The assumption is that lower level modules will
33 normally be imported before higher level modules and thus must be cleaned up
34 later.
35
36 If an exception is raised during execution of the exit handlers, a traceback is
37 printed (unless :exc:`SystemExit` is raised) and the exception information is
38 saved. After all exit handlers have had a chance to run the last exception to
39 be raised is re-raised.
40
Georg Brandl55ac8f02007-09-01 13:51:09 +000041 This function returns *func* which makes it possible to use it as a decorator
42 without binding the original name to ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +000043
44
45.. function:: unregister(func)
46
47 Remove a function *func* from the list of functions to be run at interpreter-
48 shutdown. After calling :func:`unregister`, *func* is guaranteed not to be
49 called when the interpreter shuts down.
50
Georg Brandl116aa622007-08-15 14:28:22 +000051
52.. seealso::
53
54 Module :mod:`readline`
Georg Brandlb868a662009-04-02 02:56:10 +000055 Useful example of :mod:`atexit` to read and write :mod:`readline` history
56 files.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58
59.. _atexit-example:
60
61:mod:`atexit` Example
62---------------------
63
64The following simple example demonstrates how a module can initialize a counter
65from a file when it is imported and save the counter's updated value
66automatically when the program terminates without relying on the application
67making an explicit call into this module at termination. ::
68
69 try:
Éric Araujoe4f6a802011-03-12 15:56:09 +010070 with open("/tmp/counter") as infile:
71 _count = int(infile.read())
Antoine Pitrou62ab10a02011-10-12 20:10:51 +020072 except FileNotFoundError:
Georg Brandl116aa622007-08-15 14:28:22 +000073 _count = 0
74
75 def incrcounter(n):
76 global _count
77 _count = _count + n
78
79 def savecounter():
Éric Araujoa3dd56b2011-03-11 17:42:48 +010080 with open("/tmp/counter", "w") as outfile:
81 outfile.write("%d" % _count)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 import atexit
84 atexit.register(savecounter)
85
86Positional and keyword arguments may also be passed to :func:`register` to be
87passed along to the registered function when it is called::
88
89 def goodbye(name, adjective):
Georg Brandl6911e3c2007-09-04 07:15:32 +000090 print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 import atexit
93 atexit.register(goodbye, 'Donny', 'nice')
94
95 # or:
96 atexit.register(goodbye, adjective='nice', name='Donny')
97
Christian Heimesd8654cf2007-12-02 15:22:16 +000098Usage as a :term:`decorator`::
Georg Brandl116aa622007-08-15 14:28:22 +000099
100 import atexit
101
102 @atexit.register
103 def goodbye():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000104 print("You are now leaving the Python sector.")
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106This obviously only works with functions that don't take arguments.
107
Antoine Pitrou1bdd6fd2011-01-07 18:42:21 +0000108