Skip to content

Instantly share code, notes, and snippets.

@labeneator
Last active August 29, 2015 14:03
Show Gist options
  • Save labeneator/3eead402818e5b20a984 to your computer and use it in GitHub Desktop.
Save labeneator/3eead402818e5b20a984 to your computer and use it in GitHub Desktop.
A file locker that uses the context manager.
import fcntl
class FileLock:
def __init__(self, filename, lock_type):
self.fh = open(filename, "a")
self.lock_type = lock_type
def __enter__(self):
print "Acquiring lock"
fcntl.flock(self.fh.fileno(), self.lock_type)
def __exit__(self, type, value, tb):
print "Releasing lock"
fcntl.flock(self.fh.fileno(), fcntl.LOCK_UN)
self.fh.close()
def main():
import os
import time
with FileLock("/tmp/some_lock_file", fcntl.LOCK_EX):
print "Start: %s" % time.ctime()
print "PID: %s" % os.getpid()
time.sleep(5)
print "Finish: %s" % time.ctime()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment