Skip to content

Instantly share code, notes, and snippets.

@artyom
Created September 12, 2012 09:33
Show Gist options
  • Save artyom/3705532 to your computer and use it in GitHub Desktop.
Save artyom/3705532 to your computer and use it in GitHub Desktop.
*bsd/linux lockfile+pidfile as contextmanager
#!/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