libvt.contrib.subprocess

Use libvt.contrib.subprocess to drive a terminal application from synchronous Python. The session reads merged terminal output in a background thread while your caller waits for text, sends input, drains backpressure, or resizes the viewport.

>>> import sys
>>> from libvt.contrib import subprocess as sp
>>> command = [
...     sys.executable,
...     "-u",
...     "-c",
...     "print('Ready'); print('Result:', input()[::-1])",
... ]
>>> try:
...     with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child:
...         _ = child.wait_for("Ready", timeout=8)
...         child.resize(rows=8, cols=48)
...         child.send_line("pear")
...         status = child.wait(timeout=8)
...         final = child.wait_eof(timeout=8)
...         assert (status, final.snapshot.lines[2]) == (0, "Result: raep")
... except NotImplementedError:
...     pass

For commands that finish on their own, call run_terminal() with a VT geometry configuration and pass the returned CompletedTerminal directly to vt_screen() or serialize_vt_snapshot():

>>> import sys
>>> from libvt.contrib import subprocess as sp
>>> from libvt.testing import serialize_vt_snapshot
>>> try:
...     done = sp.run_terminal(
...         [sys.executable, "-c", "print('OK')"],
...         vt=sp.VT(rows=2, cols=8),
...         check=True,
...         timeout=8,
...     )
...     assert "│OK      │" in serialize_vt_snapshot(done)
... except NotImplementedError:
...     pass

Waiting, timeouts, and EOF

wait() returns the direct child’s exit status. Use wait_eof() to collect final output after every process attached to the terminal closes its terminal handles, since descendants can keep the terminal open after the direct child exits. drain() waits until all queued outbound bytes flush to the terminal. Each of wait(), wait_eof(), and drain() leaves the live handle open on timeout.

Two distinct timeout exception families apply depending on which call timed out; catching only builtin TimeoutError misses TerminalTimeoutExpired:

Call

Timeout exception

Base classes

Failure detail

wait_for()

TerminalTimeoutError

TimeoutError, LibVtError

Check .eof to distinguish an unmet predicate at terminal EOF from deadline expiry.

wait(), wait_eof(), drain(), run_terminal()

TerminalTimeoutExpired

subprocess.TimeoutExpired, LibVtError

Inspect .phase ("drain", "process", or "eof") and .capture.

run_terminal() waits for outbound input drain, child exit, and terminal EOF under a shared timeout. When check=True and the direct child exits nonzero, it raises CalledTerminalError (exposing .result). On timeout, it closes the terminal and reaps the direct child before raising TerminalTimeoutExpired. Interactive commands that wait for a prompt work with open_terminal().

Snapshots and output retention

Use a live TerminalProcess handle from its creating thread and close it via with or close(). Call wait_eof() first when descendant output matters. Capture, CompletedTerminal, and TerminalProcess implement SupportsVtTarget, so vt_screen() and serialize_vt_snapshot() accept them directly.

Each capture holds the last committed Snapshot, the bounded raw_tail (up to VT.raw_limit; 0 disables tail retention while still counting raw_total), and whether EOF was reached. Raw bytes include terminal control sequences and native console translation.

Platform notes

  • Linux / POSIX PTY: close() escalates SIGHUP, SIGTERM, and SIGKILL to the child process group. A descendant that ignores hangup can outlive the terminal after the direct child exits.

  • macOS (Darwin): A single-trampoline helper owns the controlling PTY session over a socketpair so direct-child exit leaves the terminal open for descendants; close() terminates the direct child with SIGKILL and shuts down the session leader. Opening /dev/tty can hold a Darwin kernel reference until the session closes (see Apple’s controlling-terminal driver); call close() once you have collected the output you need.

  • Windows (ConPTY): Requires ReleasePseudoConsole (Windows 11 24H2 or Windows Server 2025, build 26100; see Microsoft’s ReleasePseudoConsole documentation) to observe natural EOF after the last console client exits. close() terminates the child via TerminateProcess and closes the pseudoconsole. Pass an absolute executable path for consistent executable lookup across operating systems.

API reference

Drive a child through a terminal from synchronous Python.

class libvt.contrib.subprocess.VT
class libvt.contrib.subprocess.VT

Bases: object

Set initial geometry and retention limits for a terminal child.

exception libvt.contrib.subprocess.CalledTerminalError
exception[source]
exception[source]
exception libvt.contrib.subprocess.CalledTerminalError

Bases: LibVtError, CalledProcessError

Raised when a terminal child exits with a nonzero status.

class libvt.contrib.subprocess.Capture
class libvt.contrib.subprocess.Capture

Bases: object

Hold the viewport and bounded tail of merged terminal output.

class libvt.contrib.subprocess.CompletedTerminal
class libvt.contrib.subprocess.CompletedTerminal

Bases: Capture

Hold the final capture and direct child’s exit status.

class libvt.contrib.subprocess.TerminalProcess
class libvt.contrib.subprocess.TerminalProcess

Bases: object

Control a terminal child from the thread that opened it.

Obtain a handle from open_terminal(). Use the context manager or call close() to shut down the terminal and reap the child.

exception libvt.contrib.subprocess.TerminalTimeoutExpired
exception[source]
exception[source]
exception libvt.contrib.subprocess.TerminalTimeoutExpired

Bases: LibVtError, TimeoutExpired

Raised when waiting for child exit, terminal EOF, or outbound drain expires.

libvt.contrib.subprocess.open_terminal(args, *, vt=VT(), cwd=None, env=None)
function[source]
function[source]
libvt.contrib.subprocess.open_terminal(args, *, vt=VT(), cwd=None, env=None)

Start a child with a POSIX PTY or Windows pseudoconsole.

Parameters:
  • args (collections.abc.Sequence[str]) – Executable and arguments as a nonempty sequence, such as a list.

  • vt (VT) – Terminal geometry and retention limits.

  • cwd (str | os.PathLike[str] | None) – Child working directory. Defaults to the parent’s directory.

  • env (collections.abc.Mapping[str, str] | None) – Replacement child environment. Defaults to the parent’s environment. POSIX supplies TERM=xterm-256color when missing.

Returns:

Open handle that owns merged output and must be closed.

Return type:

TerminalProcess

Raises:
  • TypeError – When vt, args, cwd, or env has an unsupported type.

  • NotImplementedError – When native terminal allocation is unavailable.

  • OSError – When native terminal creation or child launch fails.

  • ValueError – When arguments contain invalid values.

libvt.contrib.subprocess.run_terminal(args, *, vt=VT(), cwd=None, env=None, input=None, timeout=None, check=False)
function[source]
function[source]
libvt.contrib.subprocess.run_terminal(args, *, vt=VT(), cwd=None, env=None, input=None, timeout=None, check=False)

Run a command through a terminal and wait for exit and terminal EOF.

Parameters:
  • args (collections.abc.Sequence[str]) – Executable and arguments as a nonempty sequence, such as a list.

  • vt (VT) – Terminal geometry and retention limits.

  • cwd (str | os.PathLike[str] | None) – Child working directory. Defaults to the parent’s directory.

  • env (collections.abc.Mapping[str, str] | None) – Replacement child environment. Defaults to the parent’s environment.

  • input (collections.abc.Buffer | None) – Bytes-like input to queue after launch. Terminal input stays open.

  • timeout (float | None) – Shared time budget after launch for input drain, child exit, and terminal EOF. Native cleanup may take longer.

  • check (bool) – Raise for a nonzero exit status.

Returns:

Final terminal capture and direct child’s status.

Return type:

CompletedTerminal

Raises:
  • TypeError – When input, vt, args, cwd, or env has an unsupported type.

  • CalledTerminalError – If check is true and the direct child returns a nonzero status.

  • TerminalTimeoutExpired – If the timeout expires. The terminal closes and reaps the direct child before raising. POSIX descendants that ignore hangup can outlive the terminal.