Created
May 14, 2017 01:44
-
-
Save pansapiens/03b565c96926c94d9a4840cb9598392e to your computer and use it in GitHub Desktop.
Acquire an exclusive lock on a file (prevent two copies of a script running concurrently)
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
# Lightly modified from: https://gist.github.com/kjpgit/ceab4fc029c778dd1675bea8592e3bc1 | |
# Useful to ensure two copies of a script aren't running concurrently (assuming they use | |
# the same lock file, trying to lock it twice will raise IOError). | |
import fcntl | |
def _lock_file_exclusively(path): | |
""" | |
Open @path and lock it exlusively. | |
Return: file object, which you must maintain a reference to | |
(if it is closed, the lock is released). | |
Raises: IOError on failure | |
""" | |
print("Locking file %s" % path) | |
lock_file = open(path) | |
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) | |
return lock_file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment