Created
December 4, 2013 06:31
-
-
Save bcoughlan/7783253 to your computer and use it in GitHub Desktop.
Python global lock using files
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
from contextlib import contextmanager | |
class LockError(Exception): pass | |
@contextmanager | |
def lock(lock_filename, force_lock=False): | |
forced = False | |
lockerror = False | |
try: | |
if os.path.exists(lock_filename): | |
if not force_lock: | |
lockerror = True | |
raise LockError('Already locked') | |
forced = True | |
else: | |
with open(lock_filename, 'w') as f: | |
f.write(':)') | |
yield | |
finally: | |
if not forced and not lockerror: | |
try: | |
os.remove(lock_filename) | |
except OSError: | |
pass |
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
with lock('/tmp/something'): | |
do_something() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment