atexit
— Exit handlers¶
Theatexit
module defines functions to register and unregister cleanupfunctions. Functions thus registered are automatically executed upon normalinterpreter termination.atexit
runs these functions in thereverseorder in which they were registered; if you registerA
,B
, andC
,at interpreter termination time they will be run in the orderC
,B
,A
.
Note: The functions registered via this module are not called when theprogram is killed by a signal not handled by Python, when a Python fatalinternal error is detected, or whenos._exit()
is called.
Note: The effect of registering or unregistering functions from withina cleanup function is undefined.
Changed in version 3.7:When used with C-API subinterpreters, registered functionsare local to the interpreter they were registered in.
- atexit.register(func,*args,**kwargs)¶
Registerfunc as a function to be executed at termination. Any optionalarguments that are to be passed tofunc must be passed as arguments to
register()
. It is possible to register the same function and argumentsmore than once.At normal program termination (for instance, if
sys.exit()
is called orthe main module’s execution completes), all functions registered are called inlast in, first out order. The assumption is that lower level modules willnormally be imported before higher level modules and thus must be cleaned uplater.If an exception is raised during execution of the exit handlers, a traceback isprinted (unless
SystemExit
is raised) and the exception information issaved. After all exit handlers have had a chance to run, the last exception tobe raised is re-raised.This function returnsfunc, which makes it possible to use it as adecorator.
Warning
Starting new threads or calling
os.fork()
from a registeredfunction can lead to race condition between the main Pythonruntime thread freeing thread states while internalthreading
routines or the new process try to use that state. This can lead tocrashes rather than clean shutdown.Changed in version 3.12:Attempts to start a new thread or
os.fork()
a new processin a registered function now leads toRuntimeError
.
- atexit.unregister(func)¶
Removefunc from the list of functions to be run at interpreter shutdown.
unregister()
silently does nothing iffunc was not previouslyregistered. Iffunc has been registered more than once, every occurrenceof that function in theatexit
call stack will be removed. Equalitycomparisons (==
) are used internally during unregistration, so functionreferences do not need to have matching identities.
atexit
Example¶
The following simple example demonstrates how a module can initialize a counterfrom a file when it is imported and save the counter’s updated valueautomatically when the program terminates without relying on the applicationmaking an explicit call into this module at termination.
try:withopen('counterfile')asinfile:_count=int(infile.read())exceptFileNotFoundError:_count=0defincrcounter(n):global_count_count=_count+ndefsavecounter():withopen('counterfile','w')asoutfile:outfile.write('%d'%_count)importatexitatexit.register(savecounter)
Positional and keyword arguments may also be passed toregister()
to bepassed along to the registered function when it is called:
defgoodbye(name,adjective):print('Goodbye%s, it was%s to meet you.'%(name,adjective))importatexitatexit.register(goodbye,'Donny','nice')# or:atexit.register(goodbye,adjective='nice',name='Donny')
Usage as adecorator:
importatexit@atexit.registerdefgoodbye():print('You are now leaving the Python sector.')
This only works with functions that can be called without arguments.