On this page
  1. fcntl
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Cross-Process Exclusive File Lock (flock)
  7. 2. Querying / Setting PTY Window Size (ioctl + struct)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Constants & Attributes

fcntl

Prev: faulthandler | Up: stdlib_module | Next: filecmp
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — fcntl
Tags: #public #python3 #stdlib


Import

import fcntl

Overview

Low-level POSIX file-descriptor control (flock, lockf, ioctl, fcntl) for advisory file locking across processes and terminal/device ioctl queries (such as querying or setting PTY window size with TIOCGWINSZ/TIOCSWINSZ).

Quick Start

import fcntl
import tempfile

with tempfile.TemporaryFile() as fh:
    fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    fcntl.flock(fh.fileno(), fcntl.LOCK_UN)

Implementation Walkthrough

1. Cross-Process Exclusive File Lock (flock)

Prevent two cron jobs or CLI runs from corrupting a shared state file simultaneously:

from contextlib import contextmanager
import fcntl
from pathlib import Path

@contextmanager
def file_lock(lock_path: Path):
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open("a+", encoding="utf-8") as fh:
        fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
        try:
            yield fh
        finally:
            fcntl.flock(fh.fileno(), fcntl.LOCK_UN)

2. Querying / Setting PTY Window Size (ioctl + struct)

import fcntl
import struct
import termios

def set_pty_size(fd: int, rows: int, cols: int) -> None:
    winsize = struct.pack("HHHH", rows, cols, 0, 0)
    fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes