Skip to content

unaiverse.utils.os_fd_capture

The native networking library of the node writes its log lines straight to the file descriptors 1 and 2 of the process. Replacing sys.stdout in Python does not catch them because the library never goes through sys.stdout. FdCapture redirects the descriptor itself into a pipe and hands every line that arrives to a callback. The networking layer uses two instances (one for standard output and one for standard error) to send those lines to the P2P channel of the logger when NODE_LIBP2PLOG=1. A developer rarely needs it directly. It also works for any C extension that prints on the terminal.

import os
from unaiverse.utils.os_fd_capture import FdCapture

lines = []
with FdCapture(1, lines.append):
    os.system("echo from a child process")       # Written to fd 1 by another program
print(lines)                                     # ['from a child process']

FdCapture

FdCapture(fd: int, callback: Callable[[str], None], encoding: str = 'utf-8', errors: str = 'replace')
Source code in unaiverse/utils/os_fd_capture.py
def __init__(
        self,
        fd: int,
        callback: Callable[[str], None],
        encoding: str = "utf-8",
        errors: str = "replace",
) -> None:
    if fd not in (1, 2):
        raise ValueError(f"FdCapture only supports fd 1 (stdout) or fd 2 (stderr), got {fd}")
    self._target_fd = fd
    self._callback = callback
    self._encoding = encoding
    self._errors = errors
    self._lock = threading.Lock()
    self._active = False
    self._py_stream = None

    # Set when start() is called; cleared on stop()
    self._saved_fd: int | None = None  # dup of original fd
    self._read_fd: int | None = None  # read end of the pipe
    self._write_fd: int | None = None  # write end (dup2'd over target)
    self._thread: threading.Thread | None = None

Captures one of the two standard file descriptors.

Argument Type Default Meaning
fd int required 1 (standard output) or 2 (standard error). Any other value raises ValueError.
callback Callable[[str], None] required Called with every non-empty line stripped of its trailing newline and carriage return.
encoding str "utf-8" The encoding of the captured bytes.
errors str "replace" The error handler of the decoding.

While the capture is active, Python output takes a different path from native output. start() points sys.stdout (or sys.stderr) to a copy of the original descriptor. The print calls of Python (the screen output of the logger included) therefore keep reaching the terminal and do not enter the pipe. Only the writes to the descriptor number itself reach the callback.

The callback runs in a daemon thread named FdCapture-fd1 or FdCapture-fd2. An exception raised by the callback is ignored. A partial line still in the buffer when the pipe closes reaches the callback too. The class is a context manager and with calls start() and stop().

real_fd property

real_fd: int | None

The copy of the original descriptor while the capture is active. It is None when the capture is not active. Writing to it reaches the terminal without entering the pipe.

start

start() -> None
Source code in unaiverse/utils/os_fd_capture.py
def start(self) -> None:
    """Begin capturing. No-op if already active."""
    with self._lock:
        if self._active:
            return

        # 1. Flush the Python-level stream before touching the fd
        if self._target_fd == 1:
            sys.stdout.flush()
        else:
            sys.stderr.flush()

        # 2. Save a copy of the real FD, so we can restore it (and write to it)
        self._saved_fd = os.dup(self._target_fd)

        try:
            # 3. Create pipe
            self._read_fd, self._write_fd = os.pipe()

            # 4. Redirect target fd → write end of pipe.
            #    Python's sys.stdout/stderr still point to their original file
            #    objects, which internally hold the original fd number.  After
            #    dup2, those file objects now also write into the pipe.  We
            #    therefore reassign sys.stdout/stderr to write through saved_fd
            #    so that Logger screen output bypasses the pipe.
            assert self._write_fd is not None
            os.dup2(self._write_fd, self._target_fd)

            if self._target_fd == 1:
                assert self._saved_fd is not None
                self._py_stream = sys.stdout
                sys.stdout = open(self._saved_fd, "w",
                                  encoding=self._encoding, errors=self._errors,
                                  closefd=False)  # closefd=False: we own saved_fd
            else:
                self._py_stream = sys.stderr
                assert self._saved_fd is not None
                sys.stderr = open(self._saved_fd, "w",
                                  encoding=self._encoding, errors=self._errors,
                                  closefd=False)

            # 5. Start reader thread
            self._thread = threading.Thread(
                target=self._reader_loop,
                name=f"FdCapture-fd{self._target_fd}",
                daemon=True,
            )
            self._active = True
            assert self._thread is not None
            self._thread.start()

        except Exception:

            # Undo whatever partially succeeded, in reverse order
            if self._py_stream is not None:
                if self._target_fd == 1:
                    sys.stdout = self._py_stream
                else:
                    sys.stderr = self._py_stream
                self._py_stream = None
            try:
                if self._saved_fd is not None:
                    os.dup2(self._saved_fd, self._target_fd)  # restore the real fd first
            except OSError:
                pass
            for attr in ("_write_fd", "_read_fd", "_saved_fd"):
                fd = getattr(self, attr)
                if fd is not None:
                    try:
                        os.close(fd)
                    except OSError:
                        pass
                    setattr(self, attr, None)
            self._active = False
            self._thread = None
            raise

Starts the capture. It flushes the Python stream, duplicates the descriptor, creates a pipe, moves the write end over the descriptor with dup2, points sys.stdout or sys.stderr to the duplicate and starts the reader thread. A call on an active capture does nothing. When a step fails the method undoes the previous ones and raises the exception again.

stop

stop(timeout: float = 2.0) -> None
Source code in unaiverse/utils/os_fd_capture.py
def stop(self, timeout: float = 2.0) -> None:
    """Stop capturing and restore the original fd.  No-op if not active.

    Args:
        timeout: Seconds to wait for the reader thread to drain and exit.
    """
    with self._lock:
        if not self._active:
            return

        # 1. Restore Python-level stream
        if self._target_fd == 1:
            try:
                sys.stdout.flush()
            except Exception:
                pass
            sys.stdout = self._py_stream
        else:
            try:
                sys.stderr.flush()
            except Exception:
                pass
            sys.stderr = self._py_stream

        # 2. Restore the original OS-level fd
        assert self._saved_fd is not None
        os.dup2(self._saved_fd, self._target_fd)
        os.close(self._saved_fd)
        self._saved_fd = None

        # 3. Close write end of pipe → reader thread sees EOF
        assert self._write_fd is not None
        os.close(self._write_fd)
        self._write_fd = None

        self._active = False

    # 4. Wait for reader thread to drain (outside lock)
    if self._thread is not None:
        self._thread.join(timeout=timeout)
        self._thread = None

    # 5. Close read end
    if self._read_fd is not None:
        try:
            os.close(self._read_fd)
        except OSError:
            pass
        self._read_fd = None

Stops the capture. It restores sys.stdout or sys.stderr and the original descriptor, closes the write end of the pipe and waits up to timeout seconds (default 2.0) for the reader thread to deliver the remaining lines. A call on an inactive capture does nothing.