Skip to content

Instantly share code, notes, and snippets.

@mloberg mloberg/lock.py
Created Mar 7, 2014

Embed
What would you like to do?
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
"""
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
You can’t perform that action at this time.