In depth understanding of the atexit module in python
- 2020-05-27 05:57:49
Introduction to the atexit module
The python atexit module defines an register function to register an exit function in the python interpreter. This function is automatically executed when the interpreter normally terminates and is used to perform some resource cleanup operations. atexit executes these functions in the reverse order of registration; For example, register A, B, C, and run C, B, A in order when the interpreter terminates.
Note: if the program is abnormal crash, or through
Exit, the registered exit function will not be called.
Official document: https: / / docs python. org / 3.5 / library/atexit html
Register exit function
atexit.register(func, *args, **kargs)
Use func as the function to be executed at termination. Any optional parameter to be passed to func must be passed as a parameter
. You can register the same functions and parameters multiple times.
When the program exits, the registered functions are called in the first and last order. If the exit function throws an exception during execution, atexit prints the message for the exception and continues with the next callback until all exit functions are executed and it rethrows the last received exception.
By means of decorators:
#!/usr/bin/env python from atexit import register def main(): print('Do something.') @register def _atexit(): print('Done.') if __name__ == '__main__': main()
#!/usr/bin/env python from atexit import register def main(): #pass print('XX') def goodbye(name, adjective): print('Goodbye, %s, it was %s to meet you.' % (name, adjective)) register(goodbye, 'Donny', 'nice') # or: # register(goodbye, adjective='nice', name='Donny') if __name__ == '__main__': main()
Delete exit function [1 normally not used]
> atexit.unregister(func) >
Remove func from the list of functions that run when the interpreter is closed. call
After that, when the interpreter is closed, func will not be called, even if it has been registered multiple times. If func is not registered, then
I won't do anything.