Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.