Created
August 29, 2012 18:59
-
-
Save AnIrishDuck/3517180 to your computer and use it in GitHub Desktop.
Python flock context manager.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is nice! Weird that something like this is still not in
contextlib
orfcntl
.