Skip to content

Instantly share code, notes, and snippets.

@AnIrishDuck
Created August 29, 2012 18:59
Show Gist options
  • Save AnIrishDuck/3517180 to your computer and use it in GitHub Desktop.
Save AnIrishDuck/3517180 to your computer and use it in GitHub Desktop.
Python flock context manager.
import fcntl
from contextlib import contextmanager
@contextmanager
def flocked(fd):
""" Locks FD before entering the context, always releasing the lock. """
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
if __name__ == "__main__":
with open('test') as f:
with flocked(f):
print f.read()
@jb2170
Copy link

jb2170 commented Aug 8, 2024

This is nice! Weird that something like this is still not in contextlib or fcntl.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment