Skip to content

Instantly share code, notes, and snippets.

@mloberg
Created March 7, 2014 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloberg/9418954 to your computer and use it in GitHub Desktop.
Save mloberg/9418954 to your computer and use it in GitHub Desktop.
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