On this page
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
- POSIX-only (macOS/Linux/BSD): Not available on Windows (which uses ConPTY).
- Always close
slave_fdin the parent afterPopen(): Otherwise readingmaster_fdblocks forever after the child exits instead of raisingOSError(EIO)/ returningb"". - On Linux, EOF on
master_fdraisesOSError(errno.EIO)rather than returningb""; catchOSErrorand checke.errno == errno.EIO.
Common Functions
- pty.fork() —
fork()— Fork and make the child a session leader with a controlling terminal. - pty.openpty() —
openpty()— Open a pty master/slave pair, using os.openpty() if possible. - pty.spawn() —
spawn(argv, master_read=<function _read at 0x10a876560>, stdin_read=<function _read at 0x10a876560>)— Create a spawned process.
Linked from
Related notes
- tuts/python3/stdlib_module/pstats Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pty/fork Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pty/openpty Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pty/spawn Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pwd Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getopt Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; shared tags: #stdlib