| 1 |
:mod:`!atexit` --- Exit handlers |
| 2 |
================================ |
| 3 |
|
| 4 |
.. module:: atexit |
| 5 |
:synopsis: Register and execute cleanup functions. |
| 6 |
|
| 7 |
.. moduleauthor:: Skip Montanaro <[email protected]> |
| 8 |
.. sectionauthor:: Skip Montanaro <[email protected]> |
| 9 |
|
| 10 |
-------------- |
| 11 |
|
| 12 |
The :mod:`!atexit` module defines functions to register and unregister cleanup |
| 13 |
functions. Functions thus registered are automatically executed upon normal |
| 14 |
interpreter termination. :mod:`!atexit` runs these functions in the *reverse* |
| 15 |
order in which they were registered; if you register ``A``, ``B``, and ``C``, |
| 16 |
at interpreter termination time they will be run in the order ``C``, ``B``, |
| 17 |
``A``. |
| 18 |
|
| 19 |
**Note:** The functions registered via this module are not called when the |
| 20 |
program is killed by a signal not handled by Python, when a Python fatal |
| 21 |
internal error is detected, or when :func:`os._exit` is called. |
| 22 |
|
| 23 |
**Note:** The effect of registering or unregistering functions from within |
| 24 |
a cleanup function is undefined. |
| 25 |
|
| 26 |
.. versionchanged:: 3.7 |
| 27 |
When used with C-API subinterpreters, registered functions |
| 28 |
are local to the interpreter they were registered in. |
| 29 |
|
| 30 |
.. function:: register(func, *args, **kwargs) |
| 31 |
|
| 32 |
Register *func* as a function to be executed at termination. Any optional |
| 33 |
arguments that are to be passed to *func* must be passed as arguments to |
| 34 |
:func:`register`. It is possible to register the same function and arguments |
| 35 |
more than once. |
| 36 |
|
| 37 |
At normal program termination (for instance, if :func:`sys.exit` is called or |
| 38 |
the main module's execution completes), all functions registered are called in |
| 39 |
last in, first out order. The assumption is that lower level modules will |
| 40 |
normally be imported before higher level modules and thus must be cleaned up |
| 41 |
later. |
| 42 |
|
| 43 |
If an exception is raised during execution of the exit handlers, a traceback is |
| 44 |
printed (unless :exc:`SystemExit` is raised) and the exception information is |
| 45 |
saved. After all exit handlers have had a chance to run, the last exception to |
| 46 |
be raised is re-raised. |
| 47 |
|
| 48 |
This function returns *func*, which makes it possible to use it as a |
| 49 |
decorator. |
| 50 |
|
| 51 |
.. warning:: |
| 52 |
Starting new threads or calling :func:`os.fork` from a registered |
| 53 |
function can lead to race condition between the main Python |
| 54 |
runtime thread freeing thread states while internal :mod:`threading` |
| 55 |
routines or the new process try to use that state. This can lead to |
| 56 |
crashes rather than clean shutdown. |
| 57 |
|
| 58 |
.. versionchanged:: 3.12 |
| 59 |
Attempts to start a new thread or :func:`os.fork` a new process |
| 60 |
in a registered function now leads to :exc:`RuntimeError`. |
| 61 |
|
| 62 |
.. function:: unregister(func) |
| 63 |
|
| 64 |
Remove *func* from the list of functions to be run at interpreter shutdown. |
| 65 |
:func:`unregister` silently does nothing if *func* was not previously |
| 66 |
registered. If *func* has been registered more than once, every occurrence |
| 67 |
of that function in the :mod:`!atexit` call stack will be removed. Equality |
| 68 |
comparisons (``==``) are used internally during unregistration, so function |
| 69 |
references do not need to have matching identities. |
| 70 |
|
| 71 |
|
| 72 |
.. seealso:: |
| 73 |
|
| 74 |
Module :mod:`readline` |
| 75 |
Useful example of :mod:`!atexit` to read and write :mod:`readline` history |
| 76 |
files. |
| 77 |
|
| 78 |
|
| 79 |
.. _atexit-example: |
| 80 |
|
| 81 |
:mod:`!atexit` Example |
| 82 |
---------------------- |
| 83 |
|
| 84 |
The following simple example demonstrates how a module can initialize a counter |
| 85 |
from a file when it is imported and save the counter's updated value |
| 86 |
automatically when the program terminates without relying on the application |
| 87 |
making an explicit call into this module at termination. :: |
| 88 |
|
| 89 |
try: |
| 90 |
with open('counterfile') as infile: |
| 91 |
_count = int(infile.read()) |
| 92 |
except FileNotFoundError: |
| 93 |
_count = 0 |
| 94 |
|
| 95 |
def incrcounter(n): |
| 96 |
global _count |
| 97 |
_count = _count + n |
| 98 |
|
| 99 |
def savecounter(): |
| 100 |
with open('counterfile', 'w') as outfile: |
| 101 |
outfile.write('%d' % _count) |
| 102 |
|
| 103 |
import atexit |
| 104 |
|
| 105 |
atexit.register(savecounter) |
| 106 |
|
| 107 |
Positional and keyword arguments may also be passed to :func:`register` to be |
| 108 |
passed along to the registered function when it is called:: |
| 109 |
|
| 110 |
def goodbye(name, adjective): |
| 111 |
print('Goodbye %s, it was %s to meet you.' % (name, adjective)) |
| 112 |
|
| 113 |
import atexit |
| 114 |
|
| 115 |
atexit.register(goodbye, 'Donny', 'nice') |
| 116 |
# or: |
| 117 |
atexit.register(goodbye, adjective='nice', name='Donny') |
| 118 |
|
| 119 |
Usage as a :term:`decorator`:: |
| 120 |
|
| 121 |
import atexit |
| 122 |
|
| 123 |
@atexit.register |
| 124 |
def goodbye(): |
| 125 |
print('You are now leaving the Python sector.') |
| 126 |
|
| 127 |
This only works with functions that can be called without arguments. |