Skip to content

Instantly share code, notes, and snippets.

@baverman
Created May 25, 2018 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baverman/f5d4acb1a2c27974747d36095b4b915a to your computer and use it in GitHub Desktop.
Save baverman/f5d4acb1a2c27974747d36095b4b915a to your computer and use it in GitHub Desktop.
File lock using fcntl
@contextmanager
def lock(file_name, block=False):
fp = open(file_name, 'w')
opts = fcntl.LOCK_EX
if not block:
opts |= fcntl.LOCK_NB
try:
fcntl.lockf(fp, opts)
except IOError:
if block:
raise
yield False
else:
try:
yield True
finally:
fcntl.lockf(fp, fcntl.LOCK_UN)
fp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment