In depth understanding of the atexit module in python

  • 2020-05-27 05:57:49
  • OfStack

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 os._exit() 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 register() . 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.

The sample

By means of decorators:

#!/usr/bin/env python
from atexit import register
def main():
 print('Do something.')
def _atexit():
if __name__ == '__main__':

Non-decorative means:

#!/usr/bin/env python
from atexit import register
def main():
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__':

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 unregister() 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 unregister() I won't do anything.


Related articles: