util.terminal module¶
Terminals for an application’s command line, and the routing of its output to them:
TerminalWidget: a Tk text widget that behaves like a terminal (a prompt, typed commands, history).
PlainTextTerminal: the same interface on the real console (a REPL).
TerminalRegistry and installGlobalIORouting(): send stdout, stderr, logging and input() to the terminal of whichever window is active.
- util.terminal.PromptType = str | typing.Callable[[], str]¶
A prompt passed to a terminal can be either a string constant or a function with no parameters returning a string. Useful when you want to vary the prompt as unix shells often do.
- util.terminal.OnLineType¶
A function that a terminal will call to parse and execute a command whenever the user enters the command in the terminal’s REPL.
alias of
Callable[[str],Any|None]
- util.terminal.ResultToStringFunType¶
Since terminals are purely text based, and command can return ANY type, terminals will call a function of this type to translate the return value to a printable string. This is usually defaulted the builtin str() function, but more exotic functions can be passed in in the terminal’s constructor.
alias of
Callable[[Any],str]
- class util.terminal.AbstractTerminal(onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, **_kwargs)¶
Bases:
objectWhat a terminal does, whatever it’s drawn on: show a prompt, take a line of input and hand it to the onLine callback, and print the result.
- __init__(onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, **_kwargs) None¶
- Parameters:
onLine (Callable[[str], None]) – Callback invoked (on a background thread) for each submitted line.
prompt (str|Callable[[],str]) – The prompt string shown before each new command line.
resultToStringFun (ResultToStringFunType)
_kwargs
- onLine: Callable[[str], Any | None]¶
- _prompt: str | Callable[[], str]¶
- resultToStringFun: Callable[[Any], str]¶
- oldOut: TextIO | None¶
- oldErr: TextIO | None¶
- oldInput: Callable[[object], str] | None¶
- lastExecutionResult: Any¶
- property prompt: str¶
- Returns:
- Return type:
str
- abstractmethod input(prompt: str = '') str¶
Method to imitate buildins.input().
- Parameters:
prompt (str)
- Returns:
- Return type:
str
- abstractmethod printLine(text: str, style: str | None = None, fg: str | None = None, bg: str | None = None, font: tuple[str, int, str] | None = None) None¶
Write a line of output above the current prompt, with optional styling. Safe to call from any thread — calls from off the main thread are marshalled onto it via after().
Concrete terminal implementations may ignore the optional parameters.
- Parameters:
text (str) – The text to print.
style (Optional[str]) – Registered style name (e.g. “stdout”, “stderr”, “result”). Takes precedence over fg/bg/font.
fg (Optional[str]) – Foreground color, used only if style is not given.
bg (Optional[str]) – Background color, used only if style is not given.
font (Optional[tuple[str, int, str]]) – Font spec, used only if style is not given.
- Return type:
None
- class util.terminal.PlainTextTerminal(onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, stderrfg: str = 'red', stdoutfg: str = '', promptfg: str = 'yellow', queryfg: str = 'green', resultfg: str = 'blue', **_kwargs)¶
Bases:
AbstractTerminalNot really a terminal at all. This is a pure text interface (REPL - Real, Evaluate, Print, Loop) that expects to operate called from a command line on a regular terminal. It does VT terminal or emulator. Colors are supported to the limited extent of the VT terminals.
Instantiating this object runs the REPL, and the __init__() method does not return until the user presses ctrl-D.
- TERMINAL_SEQUENCES: dict[str, str] = {'black': '30', 'blue': '34', 'boldblack': '40', 'boldblue': '44', 'boldcyan': '46', 'boldgreen': '42', 'boldmagenta': '45', 'boldred': '41', 'boldwhite': '47', 'boldyellow': '43', 'cyan': '36', 'default': '0', 'green': '32', 'magenta': '35', 'red': '31', 'underline': '4', 'white': '37', 'yellow': '33'}¶
- static _getStyleSeq(name: str, default: str = '') str¶
- Parameters:
name (str)
default (str)
- Returns:
- Return type:
str
- __init__(onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, stderrfg: str = 'red', stdoutfg: str = '', promptfg: str = 'yellow', queryfg: str = 'green', resultfg: str = 'blue', **_kwargs) None¶
Run a plain text REPL interface.
Possible values for the various colour parameters are: default, underline, black, red, green, yellow, blue, magenta, cyan, white, boldblack, boldred, boldgreen, boldyellow, boldblue, boldmagenta, boldcyan, boldwhite.
- Parameters:
onLine (Callable[[str], None]) – Callback invoked (on a background thread) for each submitted line.
prompt (str|Callable[[],str]) – The prompt string shown before each new command line.
stderrfg – The colour of text from stderr. Default “red”.
stdoutfg – The colour of text from stdout. Default “” (terminal default).
promptfg – The colour of text for the prompt. Default “yellow”.
queryfg – The colour of text prompts from self.input(). Default “green”.
resultfg – The colour of text for command returned results. Default “blue”.
resultToStringFun (ResultToStringFunType)
_kwargs
- styleTags: dict[str, str]¶
- input(prompt: str = '') str¶
- Parameters:
prompt (str)
- Returns:
- Return type:
str
- printLine(text: str, style: str | None = None, fg: str | None = None, bg: str | None = None, font: tuple[str, int, str] | None = None) None¶
Write a line of output above the current prompt, with optional styling. Safe to call from any thread — calls from off the main thread are marshalled onto it via after().
- Parameters:
text (str) – The text to print.
style (Optional[str]) – Registered style name (e.g. “stdout”, “stderr”, “result”). Takes precedence over fg/bg/font.
fg (Optional[str]) – Foreground color, used only if style is not given.
bg (Optional[str]) – Background color, used only if style is not given.
font (Optional[tuple[str, int, str]]) – Font spec, used only if style is not given.
- Return type:
None
- class util.terminal.LineBufferedStream¶
Bases:
TextIOBaseBase class for file-like stream wrappers that buffer writes by line and hand each complete line to a subclass for emission.
Subclasses implement _emitLine() to decide how a line actually gets displayed (e.g. ANSI escape codes for a text console, or styled inserts into a Tk widget).
- Return type:
None
- __init__() None¶
- write(text: str) int¶
Buffer incoming text and flush complete lines via _emitLine().
- Parameters:
text (str) – Text written by print() or similar.
- Returns:
Number of characters accepted.
- Return type:
int
- flush() None¶
Flush any partial (no trailing newline) buffered text as a final line.
- Return type:
None
- _emitLine(line: str, end: str = '\n') None¶
Emit one complete line (no trailing newline). Subclasses must override.
- Parameters:
line (str) – The line to emit.
end (str)
- Return type:
None
- _abc_impl = <_abc._abc_data object>¶
- class util.terminal.LineFilteringStream(target: TextIO, transform: Callable[[str], str | None] | None = None)¶
Bases:
LineBufferedStreamApplies a transform to each complete line, then forwards it to an underlying stream (e.g. real stdout/stderr in a text console, using ANSI escape codes for color).
- Parameters:
target (TextIO) – The underlying stream to write transformed lines to.
transform (Optional[Callable[[str], Optional[str]]]) – Function applied to each line. Return None to suppress (drop) a line entirely. Defaults to passing lines through unchanged.
- __init__(target: TextIO, transform: Callable[[str], str | None] | None = None) None¶
- Parameters:
target (TextIO)
transform (Optional[Callable[[str], Optional[str]]])
- _emitLine(line: str, end: str = '\n') None¶
Apply the transform and write the result to the target stream, unless the transform suppressed the line.
- Parameters:
line (str) – The line to emit.
end (str)
- Return type:
None
- flush() None¶
Flush buffered content, then the underlying target stream.
- Return type:
None
- _abc_impl = <_abc._abc_data object>¶
- util.terminal.writeToRealConsole(text: str, style: str | None = None) None¶
Last-resort output path: write directly to the real console, bypassing routing entirely. Used when TerminalRegistry.resolveTerminal() can’t find ANY terminal to route to, so output is never silently dropped — just less conveniently placed than it would be in a TerminalWidget.
Deliberately targets sys.__stdout__/__stderr__ (the interpreter’s original streams, unaffected by installGlobalIORouting()’s reassignment of sys.stdout/sys.stderr) rather than the current sys.stdout/sys.stderr, which would just loop back into routing and hit this same fallback again.
- Parameters:
text (str) – The text to write (a newline is appended).
style (Optional[str]) – “stderr” routes to sys.__stderr__; anything else (including None) routes to sys.__stdout__.
- Return type:
None
- class util.terminal.TerminalRegistry¶
Bases:
objectRoutes stdio/logging/input() output to the correct TerminalWidget.
- Return type:
None
- __init__() None¶
- _byThread: dict[int, TerminalWidget]¶
- _focusedMainThreadTarget: TerminalWidget | None¶
- _windows: dict[Misc, TerminalWidget]¶
- registerWindow(window: Misc, terminal: TerminalWidget) None¶
Record which terminal belongs to a given top-level window, so it can be found by resolveTerminal()’s active-window fallback even if that window’s widgets never actually took Tk keyboard focus (e.g. a right-click that only ever posts a popup menu). Call this once, when the window is built.
- Parameters:
window (tk.Misc) – The Toplevel (or any of its ancestors’ Tk path resolves to it) that owns terminal.
terminal (TerminalWidget) – This window’s terminal.
- Return type:
None
- unregisterWindow(window: Misc) None¶
Remove a window’s entry once it’s closed.
- Parameters:
window (tk.Misc) – The window previously passed to registerWindow().
- Return type:
None
- bindThreadToTerminal(terminal: TerminalWidget, thread: Thread | None = None) None¶
Associate a thread with a specific terminal for the lifetime of its work. Call this from the code that STARTS the thread (e.g. a window’s command dispatch, or the graphics editor launching a background computation).
- Parameters:
terminal (TerminalWidget) – The terminal that output from this thread should route to.
thread (Optional[threading.Thread]) – The thread to bind. Defaults to the current thread.
- Return type:
None
- unbindThread(thread: Thread | None = None) None¶
Remove a thread’s routing entry once its work is done.
- Parameters:
thread (Optional[threading.Thread]) – The thread to unbind. Defaults to the current thread.
- Return type:
None
- resolveTerminal() TerminalWidget | None¶
Determine which terminal the current call should route to.
- Returns:
The bound terminal for this thread, or (for the main thread, when unbound) the focused terminal, falling back to whichever registered window’s terminal is currently active per the window manager if nothing has explicitly taken Tk focus. None if nothing resolves.
- Return type:
Optional[TerminalWidget]
- _resolveActiveWindowTerminal() TerminalWidget | None¶
Fallback for resolveTerminal(): find the terminal for whichever registered window is currently frontmost, per the window manager’s stacking order — independent of Tk’s logical keyboard focus.
This covers cases _focusedMainThreadTarget can’t: a click that never moves Tk focus (e.g. SNCanvas’s right-click popup menu), or an exception raised before the user has interacted with the window at all (e.g. during initial model population). ‘wm stackorder’ reports windows lowest-to-highest, so the LAST element is topmost.
Confirmed empirically (headless Tk) that ‘wm stackorder’ must be queried THROUGH THE APPLICATION ROOT (_root()) to get the full sibling list — querying it via one of the child Toplevels themselves returns only that single window, not its siblings, presumably because stacking-group membership is keyed off the group leader (the hidden root here), not off each Toplevel’s Python-level .master.
- Return type:
Optional[TerminalWidget]
- Returns:
- onFocusIn(terminal: TerminalWidget) None¶
Set the default routing target for interactive (main-thread) actions.
- Parameters:
terminal (TerminalWidget) – The terminal belonging to the window that gained focus.
- Return type:
None
- onFocusOut(terminal: TerminalWidget) None¶
Clear the default target if this terminal’s window is the one losing focus.
- Parameters:
terminal (TerminalWidget) – The terminal belonging to the window that lost focus.
- Return type:
None
- util.terminal._exists(widget: Misc) bool¶
- Returns:
Whether widget hasn’t been destroyed.
- class util.terminal.LineBufferedRoutingStream(registry: TerminalRegistry, style: str | None = None)¶
Bases:
TextIOBaseA file-like object that buffers writes by line and routes each complete line to whichever terminal the TerminalRegistry resolves to at write time.
- Parameters:
registry (TerminalRegistry) – The shared registry used to resolve the target terminal.
style (Optional[str]) – Style name to use when printing (e.g. “stdout”, “stderr”).
- __init__(registry: TerminalRegistry, style: str | None = None) None¶
- Parameters:
registry (TerminalRegistry)
style (Optional[str])
- write(text: str) int¶
Buffer incoming text and route complete lines to the resolved terminal.
- Parameters:
text (str) – Text written by print() or similar.
- Returns:
Number of characters accepted.
- Return type:
int
- flush() None¶
Emit any partial (no trailing newline) buffered text as a final line.
- Return type:
None
- _emit(line: str) None¶
Resolve the current target terminal and print the line to it.
Falls back to the real console (sys.__stdout__/__stderr__, per style) if no terminal resolves at all — e.g. an unbound background thread with no window ever focused or found active — so output is never silently lost, just less conveniently placed.
- Parameters:
line (str) – The line to emit.
- Return type:
None
- _abc_impl = <_abc._abc_data object>¶
- class util.terminal.TerminalLogHandler(registry: TerminalRegistry)¶
Bases:
HandlerA logging.Handler that routes formatted records to whichever terminal the TerminalRegistry resolves to at emit time.
- Parameters:
registry (TerminalRegistry) – The shared registry used to resolve the target terminal.
- __init__(registry: TerminalRegistry) None¶
- Parameters:
registry (TerminalRegistry)
- emit(record: LogRecord) None¶
Format and route a log record to the resolved terminal, styled by level.
Falls back to the real console if no terminal resolves at all — this is what previously let an exception logged from a Tk callback (e.g. Subject._notify() catching an Observer’s exception) vanish until the separately-buffered log file eventually flushed.
- Parameters:
record (logging.LogRecord) – The log record to emit.
- Return type:
None
- util.terminal.installGlobalIORouting(registry: TerminalRegistry | None = None) None¶
Install stdout/stderr/input() redirection and logging routing ONCE, for the lifetime of the application. Safe to call more than once with the same registry — later calls are a no-op. TerminalWidget calls this itself, so a simple, single-terminal app never has to call it explicitly.
- Parameters:
registry (Optional[TerminalRegistry]) – The shared registry that resolves which terminal each call routes to. Defaults to the module-level singleton (terminalRegistry) — a simple, single-terminal app doesn’t need to know TerminalRegistry exists at all.
- Return type:
None
- util.terminal.inputAsync(prompt: object = '', onResult: Callable[[str], None] | None = None, onError: Callable[[BaseException], None] | None = None, registry: TerminalRegistry | None = None) None¶
Module-level counterpart to the routed builtin input() — but safe to call from the main/GUI thread (e.g. a menu command or button handler, as in SNCanvas.makeMenu()). Resolves the target terminal the same way the routed input() does (the focused terminal, for main-thread callers), then delegates to that terminal’s TerminalWidget.inputAsync(). Use this from code that doesn’t hold a reference to any particular TerminalWidget; call the method directly on a widget instead if you already have one.
- Parameters:
prompt (object) – The prompt to display.
onResult (Optional[Callable[[str], None]]) – Called on the main thread with the line the user typed.
onError (Optional[Callable[[BaseException], None]]) – Called on the main thread with any exception raised (e.g. EOFError on Ctrl+D). If omitted, the exception is logged and swallowed.
registry (Optional[TerminalRegistry]) – Defaults to the module-level singleton (terminalRegistry).
- Return type:
None
- Raises:
RuntimeError – If no terminal can be resolved (nothing focused).
- class util.terminal.TerminalWidget(master: ~tkinter.Widget, onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, registry: ~util.terminal.TerminalRegistry | None = None, stdoutfg: str = 'black', stderrfg: str = 'red', promptfg: str = 'darkgreen', queryfg: str = 'violet red', resultfg: str = 'purple4', queryFont: tuple[str, int, str] | None = None, queryFlashColor: str | None = 'yellow', queryFlashCount: int = 6, queryFlashIntervalMs: int = 150, errorFlashCount: int = 0, errorBurstGapMs: int = 500, **kwargs: object)¶
Bases:
AbstractTerminal,TextA Text widget that behaves like a simple terminal.
- Parameters:
master (tk.Widget) – The parent Tk widget.
onLine (Callable[[str], Any]) – Callback invoked (on a background thread) for each submitted line. May return a value — if non-None, it is converted via resultToStringFun and printed with the “result” style.
prompt (PromptType) – The prompt shown before each new command line. Either a plain string, or a zero-argument callable re-evaluated on every prompt write (e.g. a bound method that reflects current state).
registry (Optional[TerminalRegistry]) – The shared TerminalRegistry used for stdio/input() routing. Global streams (sys.stdout, sys.stderr, builtins.input) and logging are expected to already be installed once at app startup via installGlobalIORouting(registry) — this widget only binds/unbinds its own worker thread against that registry. Defaults to the module-level singleton (terminalRegistry) — a simple, single-TerminalWidget app doesn’t need to know TerminalRegistry exists at all.
resultToStringFun (Optional[Callable[[Any], str]]) – Converts a non-None onLine() return value to a string for display. Defaults to str().
stdoutfg (str) – Foreground color for stdout-routed lines.
stderrfg (str) – Foreground color for stderr-routed lines.
promptfg (str) – Foreground color for the command prompt.
queryfg (str) – Foreground color for input()-style query prompts.
resultfg (str) – Foreground color for onLine()’s returned result.
queryFont (Optional[tuple[str, int, str]]) – Font spec (family, size, style) for input()-style query prompts, e.g. (“Helvetica”, 12, “bold”). Defaults to a bold variant of the widget’s own font, so a pending input() request stands out from ordinary output even without any styling of your own.
queryFlashColor (Optional[str]) – Background color the widget flashes to draw attention to a pending input() request. Set to None to disable flashing entirely.
queryFlashCount (int) – Number of on/off flashes to run when input() is called. The flash stops early, automatically, once the reply arrives.
queryFlashIntervalMs (int) – Milliseconds between flash transitions.
errorFlashCount (int) – Number of on/off flashes (in queryFlashColor) to run when a warning, error or exception – anything printed in the “stderr” style – arrives. A burst of such lines (a traceback, several log lines in a row) gets one flash: another starts only once the widget has stopped flashing and no “stderr” line has arrived for errorBurstGapMs. 0 turns it off.
errorBurstGapMs (int) – Milliseconds without a “stderr” line that end a burst.
kwargs (object) – Forwarded to tk.Text (e.g. bg, fg, font, width, height).
- __init__(master: ~tkinter.Widget, onLine: ~typing.Callable[[str], ~typing.Any | None], prompt: str | ~typing.Callable[[], str] = '> ', resultToStringFun: ~typing.Callable[[~typing.Any], str] = <class 'str'>, registry: ~util.terminal.TerminalRegistry | None = None, stdoutfg: str = 'black', stderrfg: str = 'red', promptfg: str = 'darkgreen', queryfg: str = 'violet red', resultfg: str = 'purple4', queryFont: tuple[str, int, str] | None = None, queryFlashColor: str | None = 'yellow', queryFlashCount: int = 6, queryFlashIntervalMs: int = 150, errorFlashCount: int = 0, errorBurstGapMs: int = 500, **kwargs: object) None¶
- Parameters:
master (tk.Widget)
onLine (OnLineType)
prompt (PromptType)
resultToStringFun (ResultToStringFunType)
registry (Optional[TerminalRegistry])
stdoutfg (str)
stderrfg (str)
promptfg (str)
queryfg (str)
resultfg (str)
queryFont (Optional[tuple[str, int, str]])
queryFlashColor (Optional[str])
queryFlashCount (int)
queryFlashIntervalMs (int)
errorFlashCount (int)
errorBurstGapMs (int)
kwargs (object)
- registry: TerminalRegistry¶
- history: list[str]¶
- historyIndex: int | None¶
- styleTags: dict[str, str]¶
- adHocTagCache: dict[tuple, str]¶
- _workerThread: Thread | None¶
- _replyQueue: Queue[object]¶
- _awaitingReply: bool¶
- queryFlashColor: str¶
- _flashJob: str | None¶
- _lastErrorTime: float | None¶
- _atLineStart() bool¶
Whether the widget is positioned at the start of a fresh line — either because it’s still empty, or because the last character written was a newline.
- Returns:
True if a prompt can be written without first breaking onto a new line of its own.
- Return type:
bool
- _writePrompt(text: str | None = None, style: str = 'prompt') None¶
Write a prompt (styled) and mark the start of the editable input region. Only ever appends — callers that need to replace the current line (printLine, _showInputPrompt, _finishCommand) must delete it first.
If the most recently written character isn’t a newline (e.g. output printed from a background thread that didn’t end its own line), a newline is inserted first so the prompt always starts on its own line rather than getting appended to whatever came before it.
- Parameters:
text (Optional[str]) – Prompt text to use. Defaults to the resolved self.prompt.
style (str) – Registered style to apply to the prompt text.
- Return type:
None
- _currentLine() str¶
Get the text the user has typed on the current input line.
- Returns:
The current (uncommitted) input line.
- Return type:
str
- _replaceCurrentLine(text: str) None¶
Replace the current input line with new text (used for history recall).
- Parameters:
text (str) – The text to place on the input line.
- Return type:
None
- _handleReturn(event: Event) str¶
Handle Enter: feed a pending input() request, or start a new command.
- Return type:
str
- Parameters:
event (tk.Event)
- Returns:
- _runCommand(line: str) None¶
Run onLine on a background thread, bound to THIS terminal via the registry for the duration. If onLine returns a non-None value, it is converted via resultToStringFun and printed with the “result” style. Restores the prompt when done.
- Parameters:
line (str) – The submitted command line.
- Return type:
None
- _finishCommand() None¶
Clear the current (empty) line and write a fresh command prompt. Runs on the main thread via after().
- Return type:
None
- input(prompt: str = '') str¶
Block and return a line of input, input()-style. Safe to call from onLine’s worker thread, or from any other thread that has bound itself to this terminal via the registry. Never call from the main/GUI thread.
- Parameters:
prompt (str) – The prompt text to display (uses the “query” style).
- Returns:
The line the user typed.
- Return type:
str
- Raises:
EOFError – If the user sent EOF (Ctrl+D) instead of a line.
- inputAsync(prompt: str = '', onResult: Callable[[str], None] | None = None, onError: Callable[[BaseException], None] | None = None) None¶
input(), but safe to call from the main/GUI thread — e.g. a menu command or button handler. Returns immediately; spawns a short-lived worker thread bound to this terminal that calls self.input(prompt), then marshals the result (or any exception) back onto the main thread via onResult/onError.
Calling input() directly and blocking for its return value is never safe from the main thread, no matter how you get there (a plain thread spawn included) — blocking the GUI callback on the worker thread’s result would freeze the event loop exactly as calling input() directly does. The fix is this callback/continuation style: kick off the request, return, and let onResult pick up the answer once it actually arrives.
- Parameters:
prompt (str) – The prompt text to display (uses the “query” style).
onResult (Optional[Callable[[str], None]]) – Called on the main thread with the line the user typed.
onError (Optional[Callable[[BaseException], None]]) – Called on the main thread with any exception input() raised (e.g. EOFError on Ctrl+D). If omitted, the exception is logged and otherwise swallowed.
- Return type:
None
- _showInputPrompt(prompt: str) None¶
Display an input() prompt (styled as a “query”) and mark that the next Enter is a reply, not a command. Runs on the main thread via after().
- Parameters:
prompt (str) – The prompt text.
- Return type:
None
- _startQueryFlash() None¶
Flash the widget’s background a few times to draw attention to a newly-shown input() prompt. No-ops if queryFlashColor is None. Stops automatically as soon as the reply arrives — see _stopQueryFlash(), called from _handleReturn()/_handleCtrlD() — so a fast typist never sees it run past their answer.
- Return type:
None
- flash() None¶
Flash the widget’s background a few times (as for an input() prompt: see queryFlashColor, queryFlashCount) to draw attention to something just written to it – whether or not a reply is wanted.
- Return type:
None
- _noteErrorLine() None¶
A line in the “stderr” style (a warning, an error, part of a traceback) has just been printed: flash (errorFlashCount times) if it starts a new burst. It doesn’t if the widget is already flashing, or if the previous “stderr” line came less than errorBurstGapMs ago – so a traceback, or several log lines in a row, gets one flash, not one per line.
- Return type:
None
- _flashTick(ticksRemaining: int, untilReply: bool = True) None¶
One step of the attention-flash. Alternates the widget’s background between queryFlashColor and its normal color; reschedules itself via after() until ticksRemaining reaches 0 – or, for an input() prompt, the reply arrives.
- Parameters:
ticksRemaining (int) – Number of color alternations left.
untilReply (bool) – Whether to stop when no reply is awaited (an input() prompt’s flash), or just run its course (see flash()).
- Return type:
None
- _stopQueryFlash() None¶
Cancel any in-progress input() attention-flash and restore the normal background immediately. Safe to call even when no flash is running.
- Return type:
None
- destroy() None¶
Cancel any flash in progress, so it doesn’t outlive the widget.
- Return type:
None
- _handleCtrlD(event: Event) str¶
Signal EOF to a pending input() call, mimicking terminal Ctrl+D semantics.
- Return type:
str
- Parameters:
event (tk.Event)
- Returns:
- _handleUp(event: Event) str¶
Recall the previous history entry.
- Return type:
str
- Parameters:
event (tk.Event)
- Returns:
- _handleDown(event: Event) str¶
Recall the next history entry, or clear the line at the end of history.
- Return type:
str
- Parameters:
event (tk.Event)
- Returns:
- _handleBackspace(event: Event) str | None¶
Prevent backspacing past the start of the input region.
- Return type:
Optional[str]
- Parameters:
event (tk.Event)
- Returns:
- _guardEditableRegion(event: Event) str | None¶
Block edits (other than at/after inputStart) to protect prior output.
- Return type:
Optional[str]
- Parameters:
event (tk.Event)
- Returns:
- registerStyle(name: str, fg: str | None = None, bg: str | None = None, font: tuple[str, int, str] | None = None) None¶
Register (or re-register) a named style for use by printLine/_writePrompt.
- Parameters:
name (str) – Style name, e.g. “stdout”, “stderr”, “prompt”, “query”, “result”.
fg (Optional[str]) – Foreground (text) color.
bg (Optional[str]) – Background highlight color.
font (Optional[tuple[str, int, str]]) – Font spec as (family, size, style).
- Return type:
None
- _getAdHocTag(fg: str | None, bg: str | None, font: tuple[str, int, str] | None) str¶
Get (creating and caching if necessary) a tag for an unnamed style combo.
- Parameters:
fg (Optional[str]) – Foreground color.
bg (Optional[str]) – Background color.
font (Optional[tuple[str, int, str]]) – Font spec.
- Returns:
The tag name to use for this style combination.
- Return type:
str
- printLine(text: str, style: str | None = None, fg: str | None = None, bg: str | None = None, font: tuple[str, int, str] | None = None) None¶
Write a line of output above the current prompt, with optional styling. Safe to call from any thread — calls from off the main thread are marshalled onto it via after().
- Parameters:
text (str) – The text to print.
style (Optional[str]) – Registered style name (e.g. “stdout”, “stderr”, “result”). Takes precedence over fg/bg/font.
fg (Optional[str]) – Foreground color, used only if style is not given.
bg (Optional[str]) – Background color, used only if style is not given.
font (Optional[tuple[str, int, str]]) – Font spec, used only if style is not given.
- Return type:
None
- wrap(on: bool = True)¶
- Parameters:
on (bool)
- class util.terminal._EofSentinel¶
Bases:
objectDistinct sentinel object put on the reply queue to signal EOF (Ctrl+D), distinguishable from any real string a user could type.