Home > Python > PID lock file in python

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")
        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: , ,
  1. Ff
    December 9, 2010 at 1:13 pm

    thanks, I was looking for something just like that!

  2. trout
    August 4, 2011 at 12:55 pm

    Thanks wonderfull

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: