# `libvt.contrib.subprocess`

Use {mod}`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.

```python
>>> 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
{func}`~libvt.contrib.subprocess.run_terminal` with a
{class}`~libvt.contrib.subprocess.VT` geometry configuration and pass the
returned {class}`~libvt.contrib.subprocess.CompletedTerminal` directly to
{func}`~libvt.testing.vt_screen` or
{func}`~libvt.testing.serialize_vt_snapshot`:

```python
>>> 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

{meth}`~libvt.contrib.subprocess.TerminalProcess.wait` returns the direct
child's exit status. Use
{meth}`~libvt.contrib.subprocess.TerminalProcess.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. {meth}`~libvt.contrib.subprocess.TerminalProcess.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 {exc}`TimeoutError` misses
{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`:

| Call | Timeout exception | Base classes | Failure detail |
| --- | --- | --- | --- |
| {meth}`~libvt.contrib.subprocess.TerminalProcess.wait_for` | {exc}`~libvt.exc.TerminalTimeoutError` | {exc}`TimeoutError`, {exc}`~libvt.exc.LibVtError` | Check `.eof` to distinguish an unmet predicate at terminal EOF from deadline expiry. |
| {meth}`~libvt.contrib.subprocess.TerminalProcess.wait`, {meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof`, {meth}`~libvt.contrib.subprocess.TerminalProcess.drain`, {func}`~libvt.contrib.subprocess.run_terminal` | {exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired` | {exc}`subprocess.TimeoutExpired`, {exc}`~libvt.exc.LibVtError` | Inspect `.phase` (`"drain"`, `"process"`, or `"eof"`) and `.capture`. |

{func}`~libvt.contrib.subprocess.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
{exc}`~libvt.contrib.subprocess.CalledTerminalError` (exposing `.result`). On
timeout, it closes the terminal and reaps the direct child before raising
{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`. Interactive commands
that wait for a prompt work with
{func}`~libvt.contrib.subprocess.open_terminal`.

## Snapshots and output retention

Use a live {class}`~libvt.contrib.subprocess.TerminalProcess` handle from its
creating thread and close it via `with` or
{meth}`~libvt.contrib.subprocess.TerminalProcess.close`. Call `wait_eof()`
first when descendant output matters.
{class}`~libvt.contrib.subprocess.Capture`,
{class}`~libvt.contrib.subprocess.CompletedTerminal`, and
{class}`~libvt.contrib.subprocess.TerminalProcess` implement
{class}`~libvt.testing.SupportsVtTarget`, so
{func}`~libvt.testing.vt_screen` and
{func}`~libvt.testing.serialize_vt_snapshot` accept them directly.

Each capture holds the last committed {class}`~libvt.snapshot.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](https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/kern/tty_tty.c));
  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](https://learn.microsoft.com/en-us/windows/console/releasepseudoconsole))
  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

```{eval-rst}
.. automodule:: libvt.contrib.subprocess
   :members:
```
