Skip to content

Instantly share code, notes, and snippets.

@jmckib
Created January 26, 2011 02:08
Show Gist options
  • Select an option

  • Save jmckib/796098 to your computer and use it in GitHub Desktop.

Select an option

Save jmckib/796098 to your computer and use it in GitHub Desktop.
python file lock using flock(2) system call
Tested on Mac OS X 10.6.6 and Ubuntu 10.10 with Python 2.6.6
To try it out, open up a python shell and type:
>>> from lock import FileLock
>>> lock = FileLock("my_lock", dir="/var/tmp")
>>> lock.acquire()
Leave the first shell open, and open another python shell and type the same thing:
>>> from lock import FileLock
>>> lock = FileLock("my_lock", dir="/var/tmp")
>>> lock.acquire()
The call to lock.acquire() will block. Now in the first shell type
>>> lock.release()
and the call to lock.acquire() in the second shell will complete.
If the lock file is removed or the process holding the lock dies, the lock
will no longer be held. If you want to remove the lock file you will have to
do it yourself. See 'man 2 flock' for more details.
import fcntl
import os
class FileLock:
"""Implements a file-based lock using flock(2).
The lock file is saved in directory dir with name lock_name.
dir is the current directory by default.
"""
def __init__(self, lock_name, dir="."):
self.lock_file = open(os.path.join(dir, lock_name), "w")
def acquire(self, blocking=True):
"""Acquire the lock.
If the lock is not already acquired, return None. If the lock is
acquired and blocking is True, block until the lock is released. If
the lock is acquired and blocking is False, raise an IOError.
"""
ops = fcntl.LOCK_EX
if not blocking:
ops |= fcntl.LOCK_NB
fcntl.flock(self.lock_file, ops)
def release(self):
"""Release the lock. Return None even if lock not currently acquired"""
fcntl.flock(self.lock_file, fcntl.LOCK_UN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment