Skip to content

Commit eaa0410

Browse files
committed
contrib(feat): Drive terminal subprocesses
why: Synchronous tests need real PTY or ConPTY interaction, bounded output capture, and separate child-exit vs terminal-EOF waits on top of libvt's async sessions and recorder protocol. what: - Add libvt.contrib.subprocess with VT (raw_limit >= 0), Capture, CompletedTerminal, TerminalProcess, CalledTerminalError, TerminalTimeoutExpired, open_terminal, and run_terminal without re-exporting stdlib Popen or run. - Resolve FlightRecorder via find_flight_recorder and implement SupportsVtTarget on Capture and TerminalProcess. - Add a single-trampoline Darwin PTY session owner over socket.socketpair and a Win32 ConPTY backend. - Document libvt.contrib.subprocess in docs, README, and CHANGES, and add cross-platform subprocess and Darwin helper tests. Refs #106
1 parent 0eb832a commit eaa0410

10 files changed

Lines changed: 1777 additions & 0 deletions

File tree

‎CHANGES‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@ _Notes on the upcoming release will go here._
88

99
### What's new
1010

11+
#### Drive terminal processes synchronously (#142)
12+
13+
{func}`~libvt.contrib.subprocess.open_terminal` opens an interactive child on a
14+
POSIX PTY or Windows ConPTY, returning a
15+
{class}`~libvt.contrib.subprocess.TerminalProcess` handle. Use
16+
{func}`~libvt.contrib.subprocess.run_terminal` to collect a child's exit
17+
status, final viewport, and bounded output in a
18+
{class}`~libvt.contrib.subprocess.CompletedTerminal` result. Both
19+
{class}`~libvt.contrib.subprocess.TerminalProcess` and
20+
{class}`~libvt.contrib.subprocess.Capture` implement
21+
{class}`~libvt.testing.SupportsVtTarget` for
22+
{func}`~libvt.testing.vt_screen` and
23+
{func}`~libvt.testing.serialize_vt_snapshot`.
24+
1125
#### Recorder protocol, target protocol, and state replacement (#203)
1226

1327
Pass any {class}`~libvt.recorder.TerminalRecorder` implementation to

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,8 @@ styles:
244244
(`?2026`).
245245
- Encode keyboard, mouse, focus, and paste events according to the active
246246
terminal modes.
247+
- Drive [terminal processes](https://libvt.git-pull.com/api/contrib/subprocess/)
248+
synchronously on POSIX or Windows.
247249
- Run terminal programs on POSIX PTYs or connect to `asyncio` streams.
248250

249251
Read `tmux` captures as screen cells and decode control-mode output with

‎docs/api/contrib/index.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ Decoupled `tmux` profiles, `capture-pane` decoders, multi-pane window
1212
compositing, and `-C` / `-CC` control-mode synchronization.
1313
:::
1414

15+
:::{grid-item-card} `libvt.contrib.subprocess`
16+
:link: subprocess
17+
:link-type: doc
18+
Synchronous child processes on POSIX PTYs and Windows ConPTY.
19+
:::
20+
1521
:::{grid-item-card} `libvt.contrib.syrupy`
1622
:link: syrupy
1723
:link-type: doc
@@ -30,5 +36,6 @@ fixture (`libvt[syrupy]`).
3036
:maxdepth: 2
3137
3238
tmux/index
39+
subprocess
3340
syrupy
3441
```

‎docs/api/contrib/subprocess.md‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Synchronous terminal processes
2+
3+
Use {mod}`libvt.contrib.subprocess` to drive a terminal application from
4+
synchronous Python. The session reads merged terminal output in the
5+
background while your test waits for text, sends keys, or resizes the
6+
viewport.
7+
8+
```python
9+
>>> import ctypes
10+
>>> import sys
11+
>>> from libvt.contrib import subprocess as sp
12+
>>> command = [sys.executable, "-u", "-c",
13+
... "print('Ready'); print('Result:', input()[::-1])"]
14+
>>> supported = sys.platform != "win32" or hasattr(
15+
... ctypes.WinDLL("kernel32"), "ReleasePseudoConsole",
16+
... )
17+
>>> if supported:
18+
... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child:
19+
... _ = child.wait_for("Ready", timeout=8)
20+
... child.resize(rows=8, cols=48)
21+
... child.paste("pear")
22+
... child.send_key("enter")
23+
... status = child.wait(timeout=8)
24+
... final = child.wait_eof(timeout=8)
25+
... assert status == 0 and final.snapshot.cols == 48
26+
... assert "Result: raep" in final.snapshot.text
27+
```
28+
29+
{meth}`~libvt.contrib.subprocess.TerminalProcess.wait` returns the direct
30+
child's exit status. Use
31+
{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof` to collect the
32+
final output after every process attached to the terminal has closed its
33+
terminal handles. Descendants can keep the terminal open after the direct
34+
child exits. Both waits accept timeouts and leave the live handle available
35+
when they time out.
36+
{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_for` times out through
37+
{exc}`libvt.exc.TerminalTimeoutError`.
38+
39+
For a command that finishes on its own, call
40+
{func}`~libvt.contrib.subprocess.run_terminal`. It waits for both the direct
41+
child and terminal EOF. Its timeout covers both waits after launch. It closes
42+
the terminal and reaps the direct child before raising
43+
{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`. Use the exception's
44+
`phase` and `capture` to inspect where it timed out and what it recorded. The
45+
optional `input` bytes are queued after launch. Interactive commands that
46+
wait for a prompt before accepting input work with
47+
{func}`~libvt.contrib.subprocess.open_terminal`.
48+
49+
Use the live handle from its creating thread.
50+
{meth}`~libvt.contrib.subprocess.TerminalProcess.close` and context exit shut
51+
down the terminal and may interrupt its remaining clients. Call `wait_eof()`
52+
first when their output matters. On POSIX, a descendant that ignores hangup
53+
can outlive the terminal after the direct child exits. This also applies when
54+
`run_terminal()` closes a terminal after a timeout.
55+
{class}`~libvt.contrib.subprocess.Capture`,
56+
{class}`~libvt.contrib.subprocess.CompletedTerminal`, and
57+
{class}`~libvt.contrib.subprocess.TerminalProcess` implement
58+
{class}`~libvt.testing.SupportsVtTarget` so you can pass them directly to
59+
{func}`~libvt.testing.vt_screen` and
60+
{func}`~libvt.testing.serialize_vt_snapshot`.
61+
62+
The result includes a snapshot, the retained raw tail, and the total number
63+
of recorded bytes. The terminal and recorder retain only the configured
64+
scrollback and byte tail (`raw_limit=0` disables raw tail retention while
65+
still counting `raw_total`). Raw bytes include terminal control sequences and
66+
native console translation.
67+
68+
Terminal mode uses a POSIX PTY or native ConPTY. On macOS a single-trampoline
69+
helper owns the terminal session over a socketpair so the direct child's exit
70+
leaves the terminal available to descendants.
71+
72+
Opening `/dev/tty` can leave a Darwin kernel reference to the terminal until
73+
the session closes. If that reference keeps EOF pending, use `close()` after
74+
collecting the output you need.
75+
[Apple's controlling-terminal driver](https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/kern/tty_tty.c)
76+
77+
On Windows terminal mode requires `ReleasePseudoConsole` (Windows 11 24H2 or
78+
Windows Server 2025, build 26100) to observe natural EOF after the last
79+
console client exits. Pass an absolute executable path when you need
80+
consistent executable selection across operating systems.
81+
[Microsoft's ReleasePseudoConsole documentation](https://learn.microsoft.com/en-us/windows/console/releasepseudoconsole)
82+
83+
```{eval-rst}
84+
.. automodule:: libvt.contrib.subprocess
85+
:members: VT, Capture, CompletedTerminal, TerminalProcess, CalledTerminalError, TerminalTimeoutExpired, open_terminal, run_terminal
86+
```

‎docs/api/index.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,12 @@ Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and
9292
Decoupled `tmux` `profile`, `capture`, `window`, and `control` submodules.
9393
:::
9494

95+
:::{grid-item-card} `libvt.contrib.subprocess`
96+
:link: contrib/subprocess
97+
:link-type: doc
98+
Synchronous child processes on POSIX PTYs and Windows ConPTY.
99+
:::
100+
95101
:::{grid-item-card} `libvt.contrib.syrupy`
96102
:link: contrib/syrupy
97103
:link-type: doc

‎docs/project/public-api.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ Import specialized types and helpers from their owning submodules:
4545
{mod}`~libvt.contrib.tmux.control`) — decoupled `tmux` inner-pane profiles,
4646
`capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC`
4747
control-mode parser and pane sync
48+
- {mod}`libvt.contrib.subprocess` — synchronous child processes with
49+
{func}`~libvt.contrib.subprocess.open_terminal` and
50+
{func}`~libvt.contrib.subprocess.run_terminal` on POSIX PTYs and Windows ConPTY
4851
- {mod}`libvt.contrib.syrupy` — optional `syrupy` `.ambr` adapter
4952
(`libvt[syrupy]`): {class}`~libvt.contrib.syrupy.VtSnapshotExtension` and
5053
conditional {fixture}`vt_snapshot` `pytest11` fixture

0 commit comments

Comments
 (0)