Skip to content

Instantly share code, notes, and snippets.

@bcoughlan
Created December 4, 2013 06:31
Show Gist options
  • Save bcoughlan/7783253 to your computer and use it in GitHub Desktop.
Save bcoughlan/7783253 to your computer and use it in GitHub Desktop.
Python global lock using files
from contextlib import contextmanager
class LockError(Exception): pass
@contextmanager
def lock(lock_filename, force_lock=False):
forced = False
lockerror = False
try:
if os.path.exists(lock_filename):
if not force_lock:
lockerror = True
raise LockError('Already locked')
forced = True
else:
with open(lock_filename, 'w') as f:
f.write(':)')
yield
finally:
if not forced and not lockerror:
try:
os.remove(lock_filename)
except OSError:
pass
with lock('/tmp/something'):
do_something()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment