Is there a way in Python to have a block of code always execute at the end of a program (barring a kill -9
?
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.
Is there anyway to ensure that the cleanup portion of the python script is run?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With