views:

599

answers:

4

I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.

So, is there a Python module out there which will manage the details of a PID-based lockfile?

+4  A: 

This might be of help to you: lockfile

ennuikiller
+2  A: 

If you can use GPLv2, Mercurial has a module for that:

http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py

Example usage:

from mercurial import error, lock

try:
    l = lock.lock("/path/to/lock", timeout=600) # wait at most 10 minutes
    # do something
except error.LockHeld:
     # couldn't take the lock
else:
    l.release()
tonfa
Thanks for all the other helpful answers, but this turned out to be the simplest solution, as the added mercurial dependency isn't an issue for me (I'm just using it for "little" utility scripts).
David Wolever
+2  A: 

I believe you will find the necessary information here. The page in question refers to a package for building daemons in python: this process involves creating a PID lockfile.

jldupont
+1  A: 

There is a recipe on ActiveState on creating lockfiles.

To generate the filename you can use os.getpid() to get the PID.

Andre Miller