Friday, March 6, 2009

Restrict multiple simultaneos executions of a Python program

Here you've a simple function to avoid a python script to be executed more than once at the same time:


def use_lock(func, lockfile):
if not os.path.exists(lockfile):
with open(lockfile, 'w') as f:
f.write(str(os.getpid()))
func()
os.remove(lockfile)
return True
else:
return None


To execute a function main() using a lock file "/var/run/myprogram.pid" just write:


use_lock(main, '/var/run/myprogram.pid')


Hope you find it useful.

1 comment:

  1. Since the check and lock part of the code is not atomic, I think there's a very small chance that if you run two programs, both might end up starting. Is there a way to create a lock atomically?
    Hmm, just came across this - http://stackoverflow.com/questions/489861/locking-a-file-in-python

    ReplyDelete