Python atexit模块

模块简介

从模块的名字也可以看出来,atexit模块主要的作用就是在程序即将结束之前执行的代码,atexit模块使用register函数用于注册程序退出时的回调函数,然后在回调函数中做一些资源清理的操作

该模块主要有如下两个函数

atexit.register(func, *args, **kargs) 注册函数
atexit.unregister(func) 取消注册函数


模块实例

import atexit  

def atexitFunc_1():  
    print('I am atexitFunc_1')  

def atexitFunc_2(name, age):  
    print('I am atexitFunc_2, %s is %d years old' % (name, age))  

print('I am the first output')  

atexit.register(atexitFunc_1)  
atexit.register(atexitFunc_2, 'Katherine', 20)  

#也可以使用装饰器语法  
@atexit.register 
atexit.register( 
def atexitFunc_3():  
    print('I am atexitFunc_3')  

程序的输出为:(可见调用顺序与注册顺序是相反的)

总结:如果注册顺序是A,B,C,那么最后调用的顺序是相反的,C,B,A


注意:
1,如果程序是非正常 crash,或通过 os._exit( ) 退出,注册的回调函数将不会被调用。
2,也可以通过 sys.exitfunc 来注册回调,但通过它只能注册一个回调,而且还不支持参数。
3,建议使用 atexit 来注册回调函数。

你可能感兴趣的:(python标准库)