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:
return True
return None

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

use_lock(main, '/var/run/')

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 -