Created
May 25, 2018 04:58
-
-
Save baverman/f5d4acb1a2c27974747d36095b4b915a to your computer and use it in GitHub Desktop.
File lock using fcntl
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
@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