Skip to content

Latest commit

 

History

History
268 lines (219 loc) · 11.1 KB

README.md

File metadata and controls

268 lines (219 loc) · 11.1 KB

libvt

PyPI version tests license

libvt is a headless terminal emulator and VT parser for Python. Feed it terminal output to inspect screen contents, cursor positions, and cell styles, or use it to test terminal programs.

Requires Python 3.12 or later (CPython and PyPy). Written in Python, with type annotations and no runtime dependencies.

Installation

Install with uv or pip:

$ uv add "libvt>=0.0.1a7,<0.1"
$ pip install "libvt>=0.0.1a7,<0.1"

Optional extras install the pytest fixture plugin (libvt[pytest]) or the syrupy .ambr snapshot adapter (libvt[syrupy]), for example uv add --dev "libvt[pytest]>=0.0.1a7,<0.1". libvt is in pre-alpha (0.0.1a7); pin libvt>=0.0.1a7,<0.1 while pre-1.0 releases may include breaking API changes.

Quickstart

Feed bytes and inspect snapshots

Each call to feed() updates the screen. Read term.committed for an immutable Snapshot — safe to pass across threads, holding the last completed frame during synchronized redraws (?2026) — to inspect lines, cursor position, runs, and cell styles:

import libvt
from libvt.style import AnsiColor

term = libvt.Terminal(rows=2, cols=20)
term.feed(b"booting\r\nLoading 10%")
term.feed(b"\r\x1b[2K\x1b[1;32mLoading 20%\x1b[0m\r\ndone")
snap = term.committed
assert snap.lines == ("Loading 20%", "done")
assert (snap.cursor.row, snap.cursor.col) == (1, 4)
assert snap[0, 0].style.bold and snap[0, 0].style.fg == AnsiColor.GREEN
assert snap[0].runs[0].text == "Loading 20%"

Drive a terminal program

Use libvt.contrib.subprocess (open_terminal() for interactive sessions and run_terminal() for one-shot commands) to launch a program, submit lines atomically with send_line(), and wait for screen state synchronously. It runs on POSIX PTYs and Windows ConPTY on Windows 11 24H2 or Windows Server 2025 (build 26100, which provides ReleasePseudoConsole); older Windows builds raise NotImplementedError:

import sys

from libvt.contrib import subprocess as sp

cmd = [sys.executable, "-u", "-c", "print('Quay'); print('Taken: ' + input())"]
try:
    with sp.open_terminal(cmd, vt=sp.VT(rows=4, cols=40)) as child:
        child.wait_for("Quay", timeout=8)
        child.send_line("key")
        snap = child.wait_for(lambda s: "Taken: key" in s.lines, timeout=8)
        assert "Taken: key" in snap.lines
        assert child.wait(timeout=8) == 0
except NotImplementedError:
    pass

Pass .snapshot (or .snapshot() on a live handle) to assert_screen() and assert_screen_box(); vt_screen() and serialize_vt_snapshot() accept handles and captures directly. Use libvt.aio (AsyncTerminalStream for asyncio streams and open_pty() for custom-Profile POSIX PTYs), or the vt_pty fixture from libvt[pytest] for pytest --vt-replay-dir PTY capture.

Assert screens inline

Most unit tests can stop at assert_screen_box(), which checks visible text, wide-character column alignment, and cursor coordinates inline without extra dependencies or snapshot files:

import libvt
from libvt.testing import assert_screen_box

term = libvt.Terminal(rows=2, cols=8)
term.feed_str("日本ok\r\ndone")
assert_screen_box(
    term,
    """
    ┌────────┐
    │日本ok  │
    │done    │
    └────────┘
    """,
    cursor=(1, 4),
)

Test with pytest, syrupy, diffs, and replay

For multi-row TUIs, vt_screen() and serialize_vt_snapshot() emit escape-free boxes with region= cropping, diff= transition deltas, and regex or os.PathLike (such as tmp_path) row scrubbers with zero extra dependencies. With libvt[pytest], vt_terminal and POSIX vt_pty attach a 4 KiB FlightRecorder automatically, while vt_factory defaults to recorder=None so you pass recorder=vt_recorder explicitly when you want FlightRecorder traces on assert_screen() or assert_screen_box() failures:

import pathlib

from libvt.pytest_plugin import TerminalFactory
from libvt.recorder import FlightRecorder
from libvt.testing import serialize_vt_snapshot, vt_screen


def test_status_diff(
    vt_factory: TerminalFactory,
    vt_recorder: FlightRecorder,
    tmp_path: pathlib.Path,
) -> None:
    cols = max(32, len(str(tmp_path)) + 20)
    term = vt_factory(rows=2, cols=cols, recorder=vt_recorder)
    term.feed_str(f"[ ] build  {tmp_path}\r\nwaiting")
    before = term.committed
    term.feed_str("\x1b[H[x] build\r\n\x1b[1;32mdone\x1b[0m   ")
    view = vt_screen(term, diff=before, scrubbers=[(tmp_path, "<TMP>")])
    diff = serialize_vt_snapshot(view)
    assert "row 0 cols 1..2: ' ' -> 'x'" in diff and "<TMP>" in diff
    assert "r1[0..4]: bold fg=green" in diff

Run pytest --vt-replay-dir=replays to save failing byte streams and resizes, then inspect them with python -m libvt replay --chunk-size 1 <artifact> (see Replay a failed terminal test). With libvt[syrupy], vt_snapshot persists boxed .ambr golden files through VtSnapshotExtension:

from libvt.terminal import Terminal
from libvt.testing import vt_screen
from syrupy.assertion import SnapshotAssertion


def test_banner(vt_terminal: Terminal, vt_snapshot: SnapshotAssertion) -> None:
    vt_terminal.feed_str("\x1b[1;32mREADY\x1b[0m  pid=48210\r\nok")
    view = vt_screen(vt_terminal, scrubbers=[(r"pid=\d+", "pid=<PID>")])
    assert view == vt_snapshot

Render, strip, and explain VT streams

render() emulates cursor overwrites on a rows=24, cols=80 viewport with no scrollback (newline_mode=False and unwrap=False by default; pass newline_mode=True for LF-only streams or unwrap=True to join soft-wrapped lines). strip() removes control sequences and \r without replaying cursor movement. explain() disassembles each sequence in a stream:

import libvt
from libvt.codec import explain

raw = b"Loading 10%\r\x1b[2K\x1b[32mDone\x1b[0m"
assert libvt.render(raw, rows=1, cols=20) == "Done"
assert libvt.strip(raw) == "Loading 10%Done"
assert [s.mnemonic for s in explain(raw)] == ["TEXT", "CR", "EL", "SGR", "TEXT", "SGR"]

Invoke the CLI via python -m libvt (render, strip, explain, and replay; no standalone script binary is installed):

$ printf '\033[32mDone\033[0m' | python -m libvt explain
CSI   SGR                          32m
PRINT TEXT                         'Done'
CSI   SGR                          0m

Features

  • Keep scrollback, reflow wrapped lines on resize, page history via viewport(), locate cells with find_cells(), and read completed frames during synchronized output (?2026).
  • Handle wide characters and emoji via Unicode 17 width and grapheme rules.
  • Export plain text, <pre> HTML, or replayable VT with Snapshot.format() (OutputFormat.HTML / VT), or a deterministic JSON-compatible dict via to_dict().
  • Handle sans-I/O protocols: emit query replies via drain_replies(), pick host Profile presets, bound streams with default-deny Policy and Limits, and encode keyboard, mouse, focus, and paste input for active terminal modes.
  • Track semantic shell integration (prompt_zones, cwd) and typed events (Notification, title updates).
  • Drive processes via libvt.contrib.subprocess (sync) or libvt.aio streams and POSIX PTYs (async; see the fzf cookbook).

tmux integration

libvt.contrib.tmux decodes capture-pane output, composites multi-pane layouts (composite_tmux_window()), and syncs live -C / -CC control-mode panes (TmuxPaneSync, configurable with tmux_version=):

from libvt.contrib import tmux
from libvt.style import AnsiColor

left = tmux.decode_tmux_capture(b"\x1b[1;32mBUILD PASS\x1b[0m\n", rows=2, cols=10)
right = tmux.decode_tmux_capture(b"logs: ok\n", rows=2, cols=10)
layout = tmux.parse_tmux_window_layout("21x2,0,0{10x2,0,0,1,10x2,11,0,2}")
window = tmux.composite_tmux_window(layout, {"%1": left, "%2": right})
assert window.lines == ("BUILD PASS│logs: ok", "          │")
assert window[0, 0].style.bold and window[0, 0].style.fg == AnsiColor.GREEN

See Which screen am I testing?, Migrating from pyte, or play, test, and replay The Last Beacon. Full guides and API reference are at libvt.git-pull.com.

License

MIT License. See LICENSE.