Skip to content

Instantly share code, notes, and snippets.

@obeattie
Created July 21, 2011 09:37
Show Gist options
  • Save obeattie/1096857 to your computer and use it in GitHub Desktop.
Save obeattie/1096857 to your computer and use it in GitHub Desktop.
Context manager that acquires an exclusive lock on a file during the managed block
import contextlib
import fcntl
import os
@contextlib.contextmanager
def locked_file(path, mode='w'):
"""Context manager which will lock (and return a descriptor to) the passed file path on entry. The lock is
always released on exit. Will block until the lock is obtained."""
assert os.path.exists(path)
with open(path, mode) as fp:
lock = fcntl.lockf(fp, fcntl.LOCK_EX)
try:
yield fp
finally:
fcntl.lockf(fp, fcntl.LOCK_UN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment