在Python中是否有办法让代码块始终在程序结束时执行(禁止kill -9
?
我们有一个Jenkins项目,它在构建过程中启动python脚本。如果开发人员决定中止这项工作,那么就会有很多工件可以(并且正在)影响未来的构建。
无论如何都要确保运行python脚本的清理部分吗?
答案 0 :(得分:13)
使用atexit
退出处理程序。以下是python docs:
try:
_count = int(open("counter").read())
except IOError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
open("counter", "w").write("%d" % _count)
import atexit
atexit.register(savecounter)