zc.lockfile

4.0 · active · verified Fri Apr 10

The zc.lockfile package provides a basic, portable implementation of interprocess locks using file-locking primitives. It is not specifically for locking files themselves, but rather for providing general-purpose interprocess locks with a file-based mechanism. Currently at version 4.0, the library is actively maintained with updates primarily focused on Python version compatibility and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to acquire and release an inter-process lock using `zc.lockfile.LockFile`. It includes proper error handling for when a lock cannot be acquired and ensures the lock is released in a `finally` block to prevent deadlocks. It also shows how to optionally remove the lock file after use.

import zc.lockfile
import os
import time

lock_file_path = "my_app.lock"
lock = None

try:
    # Attempt to acquire the lock
    lock = zc.lockfile.LockFile(lock_file_path)
    print(f"Process {os.getpid()}: Acquired lock on {lock_file_path}")

    # Simulate critical section work
    print(f"Process {os.getpid()}: Doing some critical work...")
    time.sleep(2) # Simulate work
    print(f"Process {os.getpid()}: Critical work complete.")

except zc.lockfile.LockError:
    print(f"Process {os.getpid()}: Could not acquire lock on {lock_file_path}. Another process holds it.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    if lock:
        lock.close()
        print(f"Process {os.getpid()}: Released lock on {lock_file_path}")
        # Optionally remove the lock file if it should not persist
        # In a real application, consider if other processes might still need to check for its existence
        try:
            os.remove(lock_file_path)
            print(f"Process {os.getpid()}: Removed lock file {lock_file_path}")
        except OSError as e:
            print(f"Process {os.getpid()}: Error removing lock file {lock_file_path}: {e}")

view raw JSON →