Archive for December, 2009

PID lock file in python

December 14, 2009 2 comments

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")
        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
                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

#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())

Hope this can help someone doing the same.

Shoaib Mir

Categories: Python Tags: , ,