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):
f = open(lockfile, 'w')
f.write(str(os.getpid()))
f.close()
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.

0 comments:

Post a Comment