Created
March 7, 2014 20:07
-
-
Save mloberg/9418954 to your computer and use it in GitHub Desktop.
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 sys | |
import fcntl | |
LOCK_EX = fcntl.LOCK_EX | |
LOCK_SH = fcntl.LOCK_SH | |
LOCK_NB = fcntl.LOCK_NB | |
class Flock(object): | |
def __init__(self, filename, flags=None, message=None): | |
self.fp = open(filename) | |
if flags is None: | |
flags = LOCK_EX | LOCK_NB | |
self.flags = flags | |
if message is None: | |
message = "%s is locked" % filename | |
self.message = message | |
def __enter__(self): | |
try: | |
fcntl.flock(self.fp.fileno(), self.flags) | |
except IOError: | |
sys.stderr.write(self.message + "\n") | |
sys.exit(1) | |
def __exit__(self, type, value, traceback): | |
if type is None or type is KeyboardInterrupt: | |
self.fp.close() | |
return True |
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
""" | |
Lock a file. | |
Only works on *nix systems | |
""" | |
import sys | |
from lock import Flock | |
with Flock(__file__): | |
print("Locked file. Hit enter to unlock") | |
dummy = sys.stdin.readline() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment