Restrict multiple simultaneos executions of a Python program

Follow me for more content or contact for work opportunities:
Twitter / LinkedIn

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.

Follow me for more content or contact for work opportunities:
Twitter / LinkedIn