grizzled.io.filelock module
This module provides portable advisory file locking primitives that operate on
file descriptors. POSIX-like systems and Windows systems use different
primitives to perform file locking, and these different primitives are modeled
by incompatible (and different) modules in the Python standard library. This
module provides an abstract FileLock
class, and underlying
implementations, to hide the operating system dependencies behind a simple
portable interface.
To create a file lock, simply instantiate the FileLock
class with an open
file descriptor. It handles the rest:
from grizzled.io.filelock import FileLock fd = open('/tmp/lockfile', 'r+') lock = FileLock(fd) lock.acquire() ... lock.release()
You can also use the locked_file()
context manager to simplify your code:
from grizzled.io.filelock import locked_file fd = open('/tmp/lockfile', 'r+') with locked_file(fd): pass # Automatically unlocked once you get here
Functions
def locked_file(
*args, **kwds)
This function is intended to be used as a with
statement context
manager. It wraps a FileLock
object so that the locking and unlocking
of the file descriptor are automatic. With the locked_file()
function,
you can replace this code:
from grizzled.io.filelock import FileLock lock = FileLock(fd) lock.acquire() try: do_something() finally: lock.release()
with this code:
from grizzled.io.filelock import locked_file with locked_file(fd): do_something()
Parameters
fd
(int
): Open file descriptor. The file must be opened for writing or updating, not reading.no_wait
(bool
): IfFalse
(the default), thenlocked_file()
will suspend the calling process if someone has the file locked. IfTrue
, thenlocked_file()
will raise anIOError
if the file is already locked by someone else.
Classes
class FileLock
A FileLock
object models a file lock. It wraps a file descriptor
and contains methods to acquire and release a lock on the file.
File lock implementations that implement this interface are guaranteed to be advisory, but not mandatory, file locks. (They may, in fact, also be mandatory file locks, but they are not guaranteed to be.)
Currently, there are underlying implementations for both POSIX systems and Windows.
Ancestors (in MRO)
- FileLock
- builtins.object
Static methods
def __init__(
self, fd)
Allocate a new file lock that operates on the specified file descriptor.
Parameters
fd
(int
): Open file descriptor. The file must be opened for writing or updating, not reading.
def acquire(
self, no_wait=False)
Lock the associated file. If someone already has the file locked,
this method will suspend the calling process, unless no_wait
is
True
.
Parameters
no_wait
(bool
): IfFalse
, thenacquire()
will suspend the calling process if someone has the file locked. IfTrue
, thenacquire()
will raise anIOError
if the file is locked by someone else.
Raises
IOError
: If the file cannot be locked for any reason.
def release(
self)
Unlock (i.e., release the lock on) the associated file.