Created
July 21, 2011 09:37
-
-
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
This file contains 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 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