2020年11月4日 / 216次阅读 / Last Modified 2020年11月4日
python3有一个atexit模块,可以用来注册程序一般退出时执行的函数,一般这些最后执行的代码要干一些清理的工作。
所谓程序一般退出场景,这两个情况是肯定符合的:
>>> import atexit
>>>
>>> def test(a,b):
... print('in the end: ', a+b)
...
>>> atexit.register(test,1,2)
>>> exit()
in the end: 3
用 atexit.register 函数注册退出时的清理函数,可以方便的传递参数。
也可以使用装饰器语法:
>>> import atexit
>>> @atexit.register
... def test():
... print('in the exit process')
...
>>> exit()
in the exit process
python官方文档说明了有一些情况无法调用到在atexit注册的函数:
The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit()
is called.
有一些信号量python没有处理,如果用这些信号量kill掉了python进程,在atexit注册的函数不会被执行;出现python fatal internal error时;调用 os._exit() 退出程序时不会执行!
关于调用 os._exit() 函数,请阅读:在python子线程中调用sys.exit的效果?
-- EOF --
本文链接:https://www.pynote.net/archives/2720
©Copyright 麦新杰 Since 2019 Python笔记