Created
September 12, 2012 09:33
-
-
Save artyom/3705532 to your computer and use it in GitHub Desktop.
*bsd/linux lockfile+pidfile as contextmanager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os, fcntl, time | |
from contextlib import contextmanager | |
@contextmanager | |
def lockfile(filename): | |
with open(filename,'a+') as lf: | |
try: | |
fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) | |
except IOError: | |
raise SystemExit('Cannot acquire lock') | |
else: | |
lf.truncate(0) | |
lf.write('%d\n' % os.getpid()) | |
lf.flush() | |
try: | |
yield | |
finally: | |
lf.truncate(0) | |
def job(foo): | |
print "Doing serious business" | |
print foo | |
time.sleep(15) | |
print "Bye" | |
if __name__ == "__main__": | |
with lockfile('LOCK'): | |
job('yo, dawg!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment