Skip to content

Instantly share code, notes, and snippets.

@pansapiens
Created May 14, 2017 01:44
Show Gist options
  • Save pansapiens/03b565c96926c94d9a4840cb9598392e to your computer and use it in GitHub Desktop.
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)
# 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