This article mainly introduces the basic example of using the atexit module in Python. the sample code is based on Python 2.x. Note that it is compatible with Python 3. if you need it, refer to the atexit module, only one register function is defined for registering the callback function when the program exits. we can perform some resource cleanup operations in this callback function.
Note: If the program is abnormal crash or exits through OS. _ exit (), the registered callback function will not be called.
You can also use sys. exitfunc to register a callback, but only one callback can be registered through it, and parameters are not supported. We recommend that you use atexit to register the callback function. But do not use both methods in the program. otherwise, callback registered through atexit may not be called normally. In fact, by checking the source code of atexit, you will find that it uses sys internally. implemented by exitfunc. it first puts the registered callback function into a list. when the program exits, it calls the registered callback in the first and later order. If the callback function throws an exception during execution, atexit prints the abnormal text information and continues executing the next callback until all the callbacks are completed, it will throw the final exception.
If the python version is 2.6, you can also use the modifier syntax to register the callback function.
The following example shows how to use the atexit module:
import atexit def exit0(*args, **kwarg): print 'exit0' for arg in args: print ' ' * 4, arg for item in kwarg.items(): print ' ' * 4, item def exit1(): print 'exit1' raise Exception, 'exit1' def exit2(): print 'exit2' atexit.register(exit0, *[1, 2, 3], **{ "a": 1, "b": 2, })atexit.register(exit1)atexit.register(exit2) @atexit.registerdef exit3(): print 'exit3' if __name__ == '__main__': pass
The following is the result of running the program. we can see that the execution sequence of the callback functions is the opposite to the order in which they are registered.