On this page
  1. pty
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Running a Subprocess Attached to a PTY (openpty + subprocess.Popen)
  7. Gotchas & Boundaries
  8. Common Functions

pty

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


Import

import pty

Overview

POSIX pseudo-terminal utilities (openpty, fork, spawn) for driving interactive terminal programs (shells, SSH, REPLs, TUIs) that behave differently when attached to a pipe versus a real TTY. Essential for terminal emulators, expect-style test harnesses, and interactive process wrappers.

Quick Start

import os
import pty

master_fd, slave_fd = pty.openpty()
try:
    assert os.isatty(slave_fd)
    os.write(slave_fd, b"hello")
    assert os.read(master_fd, 5) == b"hello"
finally:
    os.close(master_fd)
    os.close(slave_fd)

Implementation Walkthrough

1. Running a Subprocess Attached to a PTY (openpty + subprocess.Popen)

Use openpty() with subprocess.Popen (and close slave_fd in the parent immediately after spawning so EOF propagates cleanly when the child exits):

import os
import pty
import subprocess

master_fd, slave_fd = pty.openpty()
try:
    proc = subprocess.Popen(
        ["python3", "-c", "import sys; print(sys.stdout.isatty())"],
        stdin=slave_fd,
        stdout=slave_fd,
        stderr=slave_fd,
        close_fds=True,
    )
    os.close(slave_fd)
    slave_fd = -1
    out = os.read(master_fd, 1024)
    proc.wait(timeout=5)
    assert b"True" in out
finally:
    if slave_fd >= 0:
        os.close(slave_fd)
    os.close(master_fd)

Gotchas & Boundaries

Common Functions

Linked from

Related notes