Last active
August 29, 2015 14:03
-
-
Save labeneator/3eead402818e5b20a984 to your computer and use it in GitHub Desktop.
A file locker that uses the context manager.
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 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