PID lock file in python
I have a python script which when running on large disks can (rarely) run on for like more then a hour, and then I have got this cron setup which runs this script and the cron is set to run every hour. This means I can have several instances of the same Python script at one time. In order to get rid of that kind of scenario I did basic style of pid lock file implementation today:
#This is to check if there is already a lock file existing#
if os.access(os.path.expanduser("~/.lockfile.vestibular.lock"), os.F_OK):
#if the lockfile is already there then check the PID number
#in the lock file
pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "r")
pidfile.seek(0)
old_pd = pidfile.readline()
# Now we check the PID from lock file matches to the current
# process PID
if os.path.exists("/proc/%s" % old_pd):
print "You already have an instance of the program running"
print "It is running as process %s," % old_pd
sys.exit(1)
else:
print "File is there but the program is not running"
print "Removing lock file for the: %s as it can be there
because of the program last time it was run" % oldpid
os.remove(os.path.expanduser("~/.lockfile.vestibular.lock"))
#This is part of code where we put a PID file in the lock file
pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "w")
pidfile.write("%s" % os.getpid())
pidfile.close
Hope this can help someone doing the same.
—
Shoaib Mir
shoaibmir[@]gmail.com
Advertisements
thanks, I was looking for something just like that!
Thanks wonderfull