始终执行代码和python脚本的结尾 [英] Always execute Code and the end of a python script

查看:82
本文介绍了始终执行代码和python脚本的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有一种方法可以使代码块始终在程序末尾执行(除非kill -9?

Is there a way in Python to have a block of code always execute at the end of a program (barring a kill -9?

我们有一个Jenkins项目,该项目会在构建过程中启动python脚本.如果开发人员决定中止这项工作,那么就会遗留很多工件,这些工件会(并且正在)影响未来的构建.

We have a Jenkins project that launches a python script as part of the build process. If a developer decides to abort the job, then there are a lot of artifacts left lying around that can (and are) influencing future builds.

总有办法确保运行python脚本的清理部分吗?

Is there anyway to ensure that the cleanup portion of the python script is run?

推荐答案

使用atexit退出处理程序.这是来自 python文档的示例:

Use the atexit exit handlers. Here's an example from the 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)

这篇关于始终执行代码和python脚本的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆