lockfile (deprecated PyPI package)
The `lockfile` package (version 0.12.2) provides a platform-independent API for locking files across Unix and Windows, relying on atomic system calls like `link` (Unix) and `mkdir` (Windows). This package is **deprecated**, with its last release in November 2015. Users are strongly advised to use alternatives like `fasteners` or `oslo.concurrency` for file locking needs.
Warnings
- breaking The API underwent significant changes in version 0.9. Classes like `LinkFileLock`, `MkdirFileLock`, and `SQLiteFileLock` were moved from the top-level `lockfile` module into their own submodules (e.g., `lockfile.linklockfile.LinkFileLock`). The class naming convention also reversed, changing from `SomethingFileLock` to `SomethingLockFile`.
- deprecated This `lockfile` package is officially deprecated and has not been updated since November 2015. It is highly recommended to migrate to actively maintained alternatives.
- gotcha The `LockFile` implementation relies on the atomic nature of `link()` on Unix and `mkdir()` on Windows. While providing cross-platform compatibility, this mechanism might not be suitable for all network file systems (e.g., NFS), where atomic guarantees can be an issue.
- gotcha Calling `release()` on an already unlocked `LockFile` instance will raise a `LockError`. This can occur if the lock is released prematurely or if there's a logic error in handling lock states, particularly in complex multi-process scenarios or when mixing explicit `acquire`/`release` with context managers.
Install
-
pip install lockfile
Imports
- LockFile
from lockfile import LockFile
- LinkFileLock
from lockfile.linklockfile import LinkFileLock
- MkdirFileLock
from lockfile.mkdirlockfile import MkdirFileLock
Quickstart
from lockfile import LockFile
import os
lock_path = os.environ.get('LOCK_FILE_PATH', 'my_app.lock')
lock = LockFile(lock_path)
try:
print(f"Attempting to acquire lock for {lock.path}...")
lock.acquire(timeout=10) # Wait up to 10 seconds
print(f"Lock acquired for {lock.path}. Performing critical operation...")
# Simulate work
with open('shared_resource.txt', 'a') as f:
f.write('Critical operation performed.\n')
print("Critical operation complete.")
except lock.AlreadyLocked: # Using lock.AlreadyLocked for consistency across versions
print(f"Could not acquire lock for {lock.path}: Already locked by another process.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
if lock.is_locked():
lock.release()
print(f"Lock released for {lock.path}.")
else:
print(f"Lock was not acquired, so no release needed for {lock.path}.")