The Atexit module is simple enough to define a register function to register the callback function when the program exits, and we can do some cleanup of the resources in this callback function. The following article mainly introduces the Atexit module in Python data, the need for friends can refer to.
Atexit Module Introduction
The Python atexit module defines a register function for registering an exit function in the Python interpreter, which is executed automatically when the interpreter terminates normally, and is typically used to do some cleanup of resources. Atexit execute these functions in the reverse order of registration; For example, register A, B, C, and run sequentially c,b,a the interpreter terminates.
Note: If the program is abnormal crash, or by os._exit() exiting, 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 execute at termination. Any optional arguments that you want to pass to Func must be passed as arguments register() . The same functions and parameters can be registered multiple times.
When the program exits, the registered function is called in the order of advanced and out. If the Exit function throws an exception during execution, atexit prints the exception's information and proceeds to the next callback until all exit functions have finished executing, and it will re-throw the last received exception.
Example
The way through the adorner:
#!/usr/bin/env pythonfrom atexit Import registerdef main (): print (' do something. ') @registerdef _atexit (): Print (' done. ') if __name__ = = ' __main__ ': Main ()
Non-adorner way:
#!/usr/bin/env pythonfrom atexit Import registerdef Main (): #pass print (' XX ') def goodbye (name, adjective): print (' Goodbye,%s, it is%s to meet "% (name, adjective)) register (Goodbye, ' Donny ', ' Nice ') # or:# register (Goodbye, ADJEC Tive= ' Nice ', name= ' Donny ') if __name__ = = ' __main__ ': Main ()
Delete Exit Function [not commonly used]
> Atexit.unregister (func) >
The
removes Func from the list of functions that run when the interpreter shuts down. When unregister () is called, Func is not invoked when the interpreter is closed, even if it is registered more than once. If Func is not registered, unregister () will not do anything.