Python Fcntl Module
The fcntl module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines.
Note: This module is only available on Unix.
Importing the Module
import fcntl
File Locking
One of the most common uses of fcntl is for file locking using flock(). This allows you to prevent multiple processes from accessing a file simultaneously.
Operations
fcntl.LOCK_SH: Acquire a shared lock.fcntl.LOCK_EX: Acquire an exclusive lock.fcntl.LOCK_UN: Unlock.fcntl.LOCK_NB: Bitwise OR with any of the above to avoid blocking if the lock cannot be acquired immediately.
Example
import fcntl
import time
with open('example.txt', 'w') as f:
try:
# Acquire an exclusive lock
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
print("Lock acquired")
f.write("Writing to file...")
time.sleep(5) # Simulate work
except BlockingIOError:
print("File is locked by another process")
finally:
# Unlock
fcntl.flock(f, fcntl.LOCK_UN)
print("Lock released")
File Control
The fcntl() function performs the operation cmd on file descriptor fd.
import fcntl
import os
fd = os.open('example.txt', os.O_RDWR | os.O_CREAT)
# Get flags
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
print(f"Flags: {flags}")
# Set flags (e.g., add O_APPEND)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_APPEND)
os.close(fd)