Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always execute Code and the end of a python script

Tags:

python

jenkins

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?

like image 454
Devon Finninger Avatar asked Feb 19 '14 17:02

Devon Finninger


1 Answers

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)
like image 176
Jayanth Koushik Avatar answered Sep 21 '22 11:09

Jayanth Koushik