Portalocker

3.2.0 · active · verified Sat Mar 28

Portalocker is a Python library that provides an easy-to-use API for cross-platform file locking. It supports file locking on Windows, Linux, BSD, and Unix systems, and can also facilitate distributed locking using Redis. The library is actively maintained, follows Semantic Versioning, and provides a convenient context manager for lock management.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the recommended way to use `portalocker` with the `Lock` context manager to safely acquire and release file locks, ensuring data integrity across processes. It explicitly shows flushing and syncing the file content to disk.

import portalocker
import os

file_path = 'my_locked_file.txt'

# Using the Lock context manager (recommended)
# The file is created/opened with 'a' mode, preventing truncation before lock
with portalocker.Lock(file_path, timeout=5, mode='a', truncate=0) as fh:
    print(f"Acquired lock on {file_path}. PID: {os.getpid()}")
    fh.write(f"Hello from process {os.getpid()}!\n")
    fh.flush()
    os.fsync(fh.fileno())
    print("Wrote data and flushed.")
# Lock is automatically released when exiting the 'with' block
print(f"Released lock on {file_path}.")

# Example of manual locking (less common, use with care)
# try:
#     f = open(file_path, 'r+')
#     portalocker.lock(f, portalocker.LockFlags.EXCLUSIVE)
#     print(f"Manually acquired lock on {file_path}")
#     f.seek(0)
#     f.write(f"Manual write from process {os.getpid()}\n")
#     f.flush()
#     os.fsync(f.fileno())
# finally:
#     portalocker.unlock(f)
#     f.close()
#     print(f"Manually released lock on {file_path}")

view raw JSON →