click_extra.capture.recording module¶
Record the screens a terminal shows while a command writes at it.
A command that animates does not print its frames one after another: it prints
one, returns the cursor to the start of the line, and prints the next over it. A
full-screen program goes further and redraws any cell it likes. The stream
therefore says what changed, and the frames only exist once something replays
those changes against a screen. TerminalScreen
is that screen, and this module notes what it shows over time.
- click_extra.capture.recording.CSI_RE = re.compile('\\x1b\\[[0-?]*[ -/]*[@-~]')¶
One control sequence, from the escape that opens it to the final byte ending it.
Broad on purpose: a typed prompt is cut between two characters, never inside an escape, so every sequence has to be recognized whole, see
ansi_prefix(). The grammar is the oneCSI_PATTERNstates, so a sequence with an intermediate byte, like theESC [ 2 SP qsetting the cursor’s shape, counts as one too.
- click_extra.capture.recording.DEFAULT_QUANTUM = 0.01¶
Grid a recording’s frame durations are rounded onto, in seconds.
Ten milliseconds is coarser than the jitter two runs of one unchanged command differ by, and finer than any frame worth picturing: the fastest bundled spinner holds one for eighty. See
quantize().
- click_extra.capture.recording.DEFAULT_RECORDING_HOLD: float | Literal['auto'] = 'auto'¶
How long a recorded animation holds its last frame before starting over.
A recording ends somewhere, and the end is usually its point: the trail filled in, the bar run out, the outcome landed. Looping straight back gives a reader no time to read any of it, and how much time reading takes depends on how much the ending shows, so the default scales with it: see
auto_hold(). A declared animation cycles in place and ends nowhere, so it holds for nothing unless a page asks.
- click_extra.capture.recording.DEFAULT_RECORDING_BLANK = 0.6¶
Seconds of empty screen closing a recorded animation’s cycle.
Long enough to read as the loop turning over, short enough not to read as the image going blank.
- click_extra.capture.recording.DEFAULT_ROWS = 24¶
Height of the terminal a recording runs its command in, in characters.
A width is what a CLI wraps to and therefore what a capture pictures, so it is stated per recording. A height only has to be tall enough that nothing scrolls away before the screen is read, which this is.
- click_extra.capture.recording.DEFAULT_SUBMIT = 0.4¶
Seconds a finished command line waits before its output starts, by default.
The beat between the last character and the return key. Long enough that the two read as separate acts, short enough that the animation does not appear to have stalled. See
type_line().
- click_extra.capture.recording.DEFAULT_TYPING = 0.05¶
Seconds one character of a typed command line takes to appear, by default.
A brisk but readable rate: a reader follows what is being typed rather than watching a line materialize. Slower than any real typist, which is the point, since the line is there to be read and not to be raced. See
type_line().
- click_extra.capture.recording.READ_POLL = 0.02¶
Seconds a recording waits on the terminal before checking the command again.
Short enough to time a frame of the fastest bundled spinner, whose interval is 80 milliseconds, and long enough that waiting costs no measurable spin.
- click_extra.capture.recording.READ_SIZE = 65536¶
Bytes read from the terminal at once.
Well past any single frame, but a pseudo-terminal still hands a large redraw back in several reads, see
REDRAW_GAP. The screen holds a sequence split across two reads until its tail arrives.
- click_extra.capture.recording.RECORDING_TERM = 'xterm-256color'¶
Terminal a recording names to its command, through
TERM.A full-screen program looks its terminal up in the terminfo database and writes the sequences that entry lists, so the name decides the vocabulary
TerminalScreenhas to read. Stating it keeps a recording from inheriting whatever terminal it runs from, and gives a program run whereTERMis unset, like a CI runner, an entry to find at all.
- click_extra.capture.recording.REDRAW_GAP = 0.01¶
Seconds of quiet that close a redraw, in a recording read off a terminal.
A program draws a screen in one write, which a pseudo-terminal hands back in as many reads as its buffer takes. A screen noted between two of them would picture a half-drawn frame. The reads of one redraw follow each other within a fraction of a millisecond, while a program redrawing ten times a second leaves 100 milliseconds between two redraws, so this gap tells them apart.
- click_extra.capture.recording.TERMINATE_GRACE = 2.0¶
Seconds a recording waits for the command to exit after
SIGTERM.A command still running when the recording ends, by its
durationor by a Ctrl+C, getsSIGTERMfirst, to clean up after itself. One that ignores it is killed with its descendants once this grace runs out, so the recording never waits forever: seeclick_extra.execution._stop_process.
- class click_extra.capture.recording.Frame(text, duration)[source]¶
Bases:
NamedTupleOne screen a recording held, and how long it held it.
Create new instance of Frame(text, duration)
- class click_extra.capture.recording.ScreenRecorder(*, clock=<built-in function monotonic>, columns=None, rows=None, onlcr=True)[source]¶
Bases:
TextIOBaseA stream that keeps every screen written at it, and when.
Stands in for a terminal without being one. It answers
isatty()in the affirmative, which is the whole question a spinner or a progress bar asks before deciding to animate, so handing one to astreamargument records an animation in-process: no pseudo-terminal, and therefore every platform.Note
This is the path a documentation build takes.
record_command()is for a command this process does not host, which has no such stream to be handed and needs a pseudo-terminal instead.Start on a blank screen, with nothing recorded.
- Parameters:
clock (
Callable[[],float]) – what the recorder reads the time off. Stated so a test can hand it a clock that does not depend on how busy the machine is.columns (
int|None) – width of the terminal, seeTerminalScreen.rows (
int|None) – height of the terminal, seeTerminalScreen.onlcr (
bool) – whether a newline returns the cursor to the start of its row, seeTerminalScreen.
- write(text)[source]¶
Replay what was written and note the screen it leaves behind.
A write changing nothing on screen is not noted: a cursor hidden or a style opened leaves the picture as it was, and the screen it did not change keeps the time it first appeared. What is kept is one sample per distinct screen, so a long animation costs as much memory as it has screens rather than as many as it has writes.
- frames(*, end=None)[source]¶
Coalesce what was recorded into the frames the screen held.
A write changing nothing on screen is not a frame, see
write(), and neither is a screen holding nothing but blanks: an animation erases its line before printing the result underneath, and neither that erasure nor the newline ending it is a picture. Neither is a screen holding nothing but the prompt a recording drew before its command started. What is left is one frame per distinct screen, each lasting until the next replaced it.Caution
The durations are wall-clock, so they answer to how busy the machine was and differ a little between two runs of the same command. Quantize them before committing what they time.
- click_extra.capture.recording.record_command(args, *, columns=80, rows=24, background=TerminalBackground.DARK, duration=None, clock=<built-in function monotonic>)[source]¶
Run a command under a pseudo-terminal and record the screens it draws.
An animation is the one thing a pipe cannot capture. A spinner asks whether its stream is a terminal and stays silent when it is not, so a command run the ordinary way prints its result and none of the frames leading to it. Forcing color through the environment does not help: that answers a different question. Only a pseudo-terminal answers this one.
Caution
Unix only. A pseudo-terminal is
termiosandpty, neither of which Windows ships, and reaching ConPTY means a dependency. Recording a spinner this process hosts needs none of that: hand aScreenRecorderto itsstreamand it animates on any platform.The terminal this runs from is hidden from the command, see
CAPTURE_HIDDEN_TERMINAL_VARS, so one machine’s recording matches another’s.Both the command’s output and its errors are read, the spinner drawing on the latter. What comes back is timed by the wall clock and therefore differs a little between two runs: quantize the durations before committing them.
- Parameters:
args (
str|Path|None|Iterable[str|Path|None|Iterable[Iterable[str|Path|None|Iterable[TNestedArgs]]]]) – the command line, in the nested formrun_cli()accepts.columns (
int) – width of the terminal it is run in, in characters.rows (
int) – height of that terminal, in characters.background (
TerminalBackground) – chrome the recording is headed for, stated to the command the way a terminal would, seeCAPTURE_TERMINAL_HINTS.duration (
float|None) – seconds to record before stopping the command.Nonerecords until it exits on its own.clock (
Callable[[],float]) – what the recorder reads the time off.
- Return type:
- Returns:
the frames the terminal held, in order.
- Raises:
NotImplementedError – on a platform with no pseudo-terminal.
OSError – when the command cannot start.
subprocess.Popenraises aFileNotFoundErrorfor a program it cannot find, and aPermissionErrorfor a file it cannot run.
- click_extra.capture.recording.quantize(frames, quantum=0.01)[source]¶
Round each frame’s duration onto a grid, so a rerun times it the same.
A recording is timed by the wall clock, so two runs of one unchanged command differ by a few milliseconds a frame. Rounding onto a grid coarser than that jitter lands both on the same numbers, which is what an asset rewritten on every build needs to stay byte-identical.
Caution
This settles jitter and nothing else. A frame the scheduler dropped leaves a shorter recording of the same frames, which no rounding recovers. That case is answered a layer up, by
animation_digest(), which fingerprints the frames a cycle holds rather than how many of them were caught.
- click_extra.capture.recording.start_at(frames, start)[source]¶
Drop what a recording showed before
startseconds into it.The animation then opens on the screen that stood at that moment, as a player told where to start does: mpv’s
--startand thestartAtoption of asciinema’s player name the same move. It cuts the seconds a command spends warming up, like a profiler’s tables filling in from nothing.The time counts from the first frame, which is where the animation starts too, and not from the moment the command was launched. The frame on screen at
startkeeps what remains of its duration.- Parameters:
- Return type:
- Returns:
the frames from
starton.- Raises:
ValueError – when
startis negative, or when it reaches past the last frame, which would leave nothing to draw.
- click_extra.capture.recording.end_at(frames, end)[source]¶
Drop what a recording showed after
endseconds into it.The mirror of
start_at(), on the same clock: mpv pairs--startwith an--endthat stops at a time counted from the beginning, not from the start.start_at(end_at(frames, 10), 6)therefore keeps the four seconds between 6 and 10.The frame on screen at
endkeeps the part of its duration before it. A recording ending sooner is kept whole.
- click_extra.capture.recording.ansi_prefix(text, count)[source]¶
The first
countprintable characters oftext, its styling kept.Slicing a styled line by index cuts an escape sequence in half, and the remains land on the screen as the digits and brackets they are made of. Counting the printable characters alone and keeping every escape passed on the way is what avoids that, and it is also correct rather than merely safe: an escape is drawn nowhere, so the ones before a character are exactly the styling in force at it.
- Parameters:
- Return type:
- Returns:
the prefix, closed by a reset so the styling it opened ends with it.
- click_extra.capture.recording.type_line(line, *, typing=0.05, submit=0.4)[source]¶
Frames of a command line appearing one keystroke at a time.
The opening act a terminal recording is usually missing. A command records what it drew and never the invocation that drew it, so an animation starts on output arriving from nowhere. Typing the line first says where it came from, and reads as a session rather than as a clip.
Note
Ordinary frames, carrying no mechanism of their own: they prepend to a recording’s and travel through
render_svg()like any others. Everything the picture does for a frame therefore reaches these too, the gutter numbering them and the cursor following the text along, seecursor_cell().The last frame holds the finished line for
submit, which is the beat before the return key. A recording’s own frames follow it.- Parameters:
line (
str) – the command line to type, already styled as a prompt draws it, seeformat_cli_prompt().typing (
float) – seconds each character takes to appear.submit (
float) – seconds the finished line waits before whatever follows.
- Return type:
- Returns:
one frame per character, in the order they are typed. Empty for an empty line, there being nothing to type.
- Raises:
ValueError – when either duration is not positive.
- click_extra.capture.recording.record_and_render(args, *, columns=80, rows=24, background=TerminalBackground.DARK, prompt=None, duration=None, start=0.0, end=None, quantum=0.01, hold='auto', blank=0.6, speed=1.0, typing=0.0, submit=0.4, line_numbers=False, emphasize=(), cursor=None, closing_prompt=False, title='', unique_id=None, preset=None, palette=None, font_stack=None, chrome=Chrome(border=None, border_width=1, radius=None, backdrop='none', shadow=None, margin=48, padding=8, opacity=1.0, watermark='generated with click-extra', watermark_color=None))[source]¶
Record a command under a pseudo-terminal and render it as an animated SVG.
Chains
record_command(),end_at(),start_at(),quantize()andrender(), the waycapture()chains the still pipeline. The invocation stands on the screen as a shell prompt before the command starts, styled by the active theme throughformat_cli_prompt(), so the recording shows what to type to reproduce it. The command’s output lands under it, and a full-screen program’s alternate screen covers it, as on a terminal.- Parameters:
args (
str|Path|None|Iterable[str|Path|None|Iterable[Iterable[str|Path|None|Iterable[TNestedArgs]]]]) – the command line to record.columns (
int) – width of the terminal it runs in, in characters. A recording pins its width up front, so there is noautohere: the pseudo-terminal must exist before the command draws its first line.rows (
int) – height of that terminal, in characters.background (
TerminalBackground) – chrome the recording is headed for, stated to the command the way a terminal would.prompt (
str|None) – command line to display, when it differs from the one run. An empty string draws no prompt at all.duration (
float|None) – seconds to record before stopping the command.Nonerecords until it exits on its own.start (
float) – seconds of the recording to drop, counted from the first screen the command drew, seestart_at(). Zero keeps them all.end (
float|None) – seconds after that first screen to stop the recording and the command at, seeend_at().Nonerecords untildurationruns out or the command exits.quantum (
float) – grid the frame durations are rounded onto, seequantize().hold (
float|Literal['auto']) – extra seconds the last frame stays up, orAUTO_HOLD(the default here) to scale them to that frame’s line count.blank (
float) – seconds of empty screen closing the cycle.speed (
float) – how much faster to play than recorded. The typed opening is replayed at the same rate as everything else, being part of what the animation shows rather than a pause laid over it.typing (
float) – seconds each character of the prompt takes to appear, opening the animation by typing the command out. Zero draws the prompt whole from the first frame, which is what a recording carrying no opening shows. Seetype_line().submit (
float) – seconds the finished command line waits before its output starts. Unused when nothing is typed.line_numbers (
bool) – draw each line’s number in a gutter, the prompt counting as the first of them. Every frame takes the gutter of the tallest, seenumber_frames().emphasize (
Sequence[int]) – lines to draw a band behind, seerender_svg().cursor (
Cursor|None) – the terminal cursor to draw, seeCursor. It follows the text from screen to screen on its own, so a typed opening gets its caret from this and nothing else.closing_prompt (
bool) – draw the shell’s prompt under the last frame, which is where it comes back once the command exits, seeappend_prompt(). Only that frame carries it: the shell has not returned while the command is still drawing. A command stopped with the alternate screen still up gets none, as its screen is no shell’s.preset (
TerminalPreset|None) – seerender().palette (
TerminalPalette|None) – seerender().
- Return type:
- Returns:
the rendered SVG document, and the command’s exit code.
- Raises:
NotImplementedError – on a platform with no pseudo-terminal.
OSError – when the command cannot start, see
record_command().ValueError – when the command drew nothing to record, when
endis not afterstart, whenstartreaches past the last screen, or when a statedtypingorsubmitis not positive.