terminal.py
Module containing Terminal, the primary API entry point.
- class Terminal(kind: str | None = None, stream: IO[str] | None = None, force_styling: bool | None = False, kind_fallback: str = 'xterm-256color', _xtgettcap_data: TermcapResponse | None = None)[source]
An abstraction for color, style, positioning, and input in the terminal.
This keeps the endless calls to
tigetstr()andtparm()out of your code, acts intelligently when somebody pipes your output to a non-terminal, and abstracts over the complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across terminal types.Initialize the terminal.
- Parameters:
kind (str) – A terminal string used for capability database, defaults to the value of the
TERMenvironment variable when undefined. If the terminal supports XTGETTCAP extension, the ‘TN’ capability name reported has precedence over ‘kind’.stream (file) –
A file-like object representing the Terminal output. Defaults to the original value of
sys.__stdout__, likecurses.initscr()does.If
streamis not a tty, empty Unicode strings are returned for all capability values, so things like piping your program output to a pipe or file does not emit terminal sequences.force_styling (bool) –
Whether to force the emission of capabilities even if
sys.__stdout__does not seem to be connected to a terminal. If you want to force styling to not happen, useforce_styling=None.This comes in handy if users are trying to pipe your output through something like
less -ror build systems which support decoding of terminal sequences.When the OS Environment variable FORCE_COLOR or CLICOLOR_FORCE is non-empty, styling is used no matter the value specified by
force_styling.Conversely, When OS Environment variable NO_COLOR is non-empty, styling is not used no matter the value specified by
force_styling, FORCE_COLOR, or CLICOLOR_FORCE.kind_fallback (str) – Terminal kind to use as fallback when the requested
kindis not found in jinxed virtual terminfo database. Defaults to'xterm-256color'which is well supported for all capabilities used by blessed on all modern terminals.
- class CursorShape
DECSCUSR cursor shape constants accessible via Terminal.CursorShape or term.CursorShape
- BLINKING_BAR = 5
- BLINKING_BLOCK = 1
- BLINKING_UNDERLINE = 3
- COLOR_RESET_OSC = '\x1b]112\x07'
- DEFAULT = 0
- DEFAULT_STYLE = 2
- STEADY_BAR = 6
- STEADY_BLOCK = 2
- STEADY_UNDERLINE = 4
- STYLES: dict[str, int] = {'blinking_bar': 5, 'blinking_block': 1, 'blinking_underline': 3, 'default': 0, 'steady_bar': 6, 'steady_block': 2, 'steady_underline': 4}
- static sequence(style: int | str) str
Return the DECSCUSR escape sequence for the given cursor style.
- Parameters:
style – An integer constant (0-6) or a string name (e.g.
'blinking_bar').- Returns:
The escape sequence string.
- Raises:
ValueError – If style is not a valid cursor shape.
- class Decrqss
DECRQSS setting identifiers accessible via Terminal.Decrqss
- DECSACE = '*x'
- DECSASD = '$}'
- DECSCA = '"q'
- DECSCL = '"p'
- DECSCP = '*u'
- DECSCPP = '$|'
- DECSCS = '*r'
- DECSCUSR = ' q'
- DECSDDT = '$q'
- DECSDPT = '(p'
- DECSFC = '*s'
- DECSKCV = ' r'
- DECSLCK = ' v'
- DECSLPP = 't'
- DECSLRM = 's'
- DECSMBV = ' u'
- DECSNLS = '*|'
- DECSPP = '+w'
- DECSPPCS = '*p'
- DECSPRTT = '$s'
- DECSRFR = '"t'
- DECSSCLS = ' p'
- DECSSDT = '$~'
- DECSSL = 'p'
- DECSTBM = 'r'
- DECSTRL = '"u'
- DECSWBV = ' t'
- SGR = 'm'
- class DecPrivateMode(value: int)
DEC Private Mode constants accessible via Terminal.DecPrivateMode or term.DecPrivateMode
- AH1 = 24
- ALT_MODIFIED_MOUSEWHEEL = 7765
- ALT_SCREEN_AND_SAVE_CLEAR = 1049
- ALT_SCREEN_BUFFER_SWITCH = 1046
- ALT_SCREEN_BUFFER_XTERM = 1047
- ALT_SCROLL_XTERM = 1007
- ALT_SENDS_ESC = 1039
- AMBIGUOUS_WIDTH_DOUBLE_WIDTH = 8840
- AMBIGUOUS_WIDTH_REPORTING = 7700
- APPLICATION_ESCAPE_KEY = 7727
- APPLICATION_MOUSEWHEEL = 7787
- BA1 = 21
- BA2 = 22
- BIDI_ARROW_KEY_SWAPPING = 1243
- BIDI_AUTODETECTION = 2501
- BIDI_CURRENT_LINE = 7796
- BOLD_ITALIC_HIGH_INTENSITY = 1021
- BRACKETED_PASTE = 2004
- BRACKETED_PASTE_MIME = 5522
- CHARACTER_MAPPING_SERVICE = 8800
- COLOR_PALETTE_UPDATES = 2031
- DEC131TM = 53
- DECAAM = 100
- DECANM = 2
- DECARM = 8
- DECARSM = 98
- DECATCBM = 115
- DECATCUM = 114
- DECAWM = 7
- DECBBSM = 116
- DECBCMM = 65
- DECBKM = 67
- DECBPM = 55
- DECBWRM = 51
- DECCANSM = 101
- DECCAPSLK = 109
- DECCKM = 1
- DECCOLM = 3
- DECCRNLM = 40
- DECCRTSM = 97
- DECECM = 117
- DECEDM = 10
- DECEKEM = 16
- DECESKM = 104
- DECFPM = 70
- DECFWM = 111
- DECGEPM = 43
- DECGPBM = 46
- DECGPCM = 44
- DECGPCS = 45
- DECGRPM = 47
- DECHCCM = 60
- DECHDPXM = 103
- DECHEBM = 35
- DECHEM = 36
- DECHWUM = 113
- DECINLM = 9
- DECIPEM = 58
- DECKANAM = 12
- DECKBUM = 68
- DECKKDM = 59
- DECKLHIM = 110
- DECKPM = 81
- DECLTM = 11
- DECMCM = 99
- DECNAKB = 57
- DECNCSM = 95
- DECNKM = 66
- DECNRCM = 42
- DECNULM = 102
- DECNUMLK = 108
- DECOM = 6
- DECOPM = 52
- DECOSCNM = 106
- DECPCCM = 64
- DECPEX = 19
- DECPFF = 18
- DECPSM = 29
- DECPSP = 27
- DECRLCM = 96
- DECRLM = 34
- DECRPL = 112
- DECSCFDM = 13
- DECSCLM = 4
- DECSCNM = 5
- DECSDM = 80
- DECTCEM = 25
- DECTEK = 38
- DECTEM = 14
- DECTHAICM = 50
- DECTHAIM = 49
- DECTHAISCM = 90
- DECUPM = 41
- DECVCCM = 61
- DECVSSM = 69
- DECXRLM = 73
- ESC_KEY_SENDS_BACKSLASH = 7728
- EXTENDED_REVERSE_WRAPAROUND = 1045
- FAST_SCROLL = 1014
- FOCUS_IN_OUT_EVENTS = 1004
- FONT_CHANGE_REPORTING = 7767
- GRAPHEME_CLUSTERING = 2027
- GRAPHICS_POSITION = 7730
- GRAPHICS_POSITION_2 = 7780
- HP_FUNC_KEY_MODE = 1052
- INPUT_METHOD_EDITOR = 737769
- IN_BAND_WINDOW_RESIZE = 2048
- ITERM2_REPORT_KEY_UP = 1337
- KEEP_SELECTION_NO_HILITE = 1040
- KITTY_HANDLE_CTRL_C_Z = 19997
- KP_DELETE_SENDS_DEL = 1037
- LEGACY_KBD_X11R6 = 1060
- META_SENDS_ESC = 1036
- META_SETS_EIGHTH_BIT = 1034
- MINTTY_BIDI = 77096
- MIRROR_BOX_DRAWING = 2500
- MODIFIERS_ALT_NUMLOCK = 1035
- MOUSEWHEEL_REPORTING = 7786
- MOUSE_ALL_MOTION = 1003
- MOUSE_EXTENDED_SGR = 1006
- MOUSE_EXTENDED_UTF8 = 1005
- MOUSE_HILITE_TRACKING = 1001
- MOUSE_REPORT_CLICK = 1000
- MOUSE_REPORT_DRAG = 1002
- MOUSE_SGR_PIXELS = 1016
- MOUSE_URXVT = 1015
- OV1 = 20
- PASSIVE_MOUSE_TRACKING = 2029
- PK1 = 23
- RAISE_ON_CTRL_G = 1043
- READLINE_CHARACTER_QUOTING = 2005
- READLINE_MOUSE_BUTTON_1 = 2001
- READLINE_MOUSE_BUTTON_2 = 2002
- READLINE_MOUSE_BUTTON_3 = 2003
- READLINE_NEWLINE_PASTING = 2006
- REPLACEMENT_CHAR_COLOR = 85
- REPORT_GRID_CELL_SELECTION = 2030
- REUSE_CLIPBOARD_DATA = 1044
- REWRAP_ON_RESIZE_MINTTY = 7723
- SAVE_CURSOR_DECSC = 1048
- SCO_FUNC_KEY_MODE = 1053
- SCROLL_MARKERS = 7711
- SCROLL_ON_KEYPRESS_RXVT = 1011
- SCROLL_ON_TTY_OUTPUT_RXVT = 1010
- SHORTCUT_KEY_MODE = 7783
- SHOW_HIDE_SCROLLBAR = 7766
- SHOW_SCROLLBAR_RXVT = 30
- SIXEL_PRIVATE_PALETTE = 1070
- SIXEL_SCROLLING_LEAVES_CURSOR = 8452
- SUN_FUNC_KEY_MODE = 1051
- SYNCHRONIZED_OUTPUT = 2026
- SpecialInternalKitty = -1
- SpecialInternalLegacyCSIModifier = -3
- SpecialInternalModifyOtherKeys = -2
- TERMINFO_FUNC_KEY_MODE = 1050
- TEXT_REFLOW = 2028
- TTCTH = 8200
- URGENCY_ON_CTRL_G = 1042
- USE_CLIPBOARD_SELECTION = 1041
- VT220_KBD_EMULATION = 1061
- WIN32_INPUT_MODE = 9001
- WYENAT_OFF = 84
- WY_52_LINE = 83
- __getattr__(attr: str) NullCallableString | ParameterizingString | FormattingString[source]
Return a terminal capability as Unicode string.
For example,
term.boldis a unicode string that may be prepended to text to set the video attribute for bold, which should also be terminated with the pairingnormal. This capability returns a callable, so you can useterm.bold("hi")which results in the joining of(term.bold, "hi", term.normal).Compound formatters may also be used. For example:
>>> term.bold_blink_red_on_green("merry x-mas!")
For a parameterized capability such as
move(orcup), pass the parameters as positional arguments:>>> term.move(line, column)
See the manual page terminfo(5) for a complete list of capabilities and their arguments.
- property kind: str
Read-only property: Terminal kind determined on class initialization.
- Return type:
- property does_styling: bool
Read-only property: Whether this class instance may emit sequences.
- Return type:
- location(x: int | None = None, y: int | None = None) Generator[None, None, None][source]
Context manager for temporarily moving the cursor.
- Parameters:
- Returns:
a context manager.
- Return type:
Iterator
Move the cursor to a certain position on entry, do any kind of I/O, and upon exit let you print stuff there, then return the cursor to its original position:
term = Terminal() with term.location(y=0, x=0): for row_num in range(term.height-1): print('Row #{row_num}') print(term.clear_eol + 'Back to original location.')
Specify
xto move to a certain column,yto move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement.Calls cannot be nested: only one should be entered at a time.
Note
The argument order (x, y) differs from the return value order (y, x) of
get_location(), or argument order (y, x) ofmove(). This is for API Compatibility with the blessings library, sorry for the trouble!
- get_location(timeout: float = 1.0) Tuple[int, int][source]
Return tuple (row, column) of cursor position.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and the value(-1, -1)is returned without inquiry.- Parameters:
timeout (float) – Return after time elapsed in seconds with value
(-1, -1)indicating that the remote end did not respond.- Return type:
- Returns:
cursor position as tuple in form of
(y, x). Always ensure the return value is checked for(-1, -1).
The location of the cursor is determined by emitting the
u7terminal capability for the VT100 Query Cursor Position. This elicits a response from a reply string described by capabilityu6for the VT100 response.The
(y, x)return value matches the parameter order of themove_yx()capability. The following sequence should cause the cursor to not move at all:>>> term = Terminal() >>> term.move_yx(*term.get_location())
And the following should assert True with a terminal:
>>> term = Terminal() >>> given_y, given_x = 10, 20 >>> with term.location(y=given_y, x=given_x): ... result_y, result_x = term.get_location() ... >>> assert given_x == result_x, (given_x, result_x) >>> assert given_y == result_y, (given_y, result_y)
- get_fgcolor(timeout: float = 1.0, bits: int = 16) Tuple[int, int, int][source]
Return tuple (r, g, b) of default foreground color.
This returns the terminal’s default color for uncolored text, not any currently active color set by escape sequences.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and the value(-1, -1, -1)is returned without inquiry.- Parameters:
- Return type:
- Returns:
foreground color as tuple in form of
(r, g, b). When a timeout is specified, always ensure the return value is checked for(-1, -1, -1).- Raises:
ValueError – When bits is not 8 or 16.
The foreground color is determined by emitting an OSC 10 color query.
See also
get_bgcolor()for querying the background color.Note
The default return value is 16-bit, matching the XParseColor specification of the underlying protocol. For most uses, 8-bit values are preferred:
rgb = term.get_fgcolor(bits=8) term.color_rgb(*rgb) # reset foreground to default
- get_bgcolor(timeout: float = 1.0, bits: int = 16) Tuple[int, int, int][source]
Return tuple (r, g, b) of default background color.
This returns the terminal’s default background color, not any currently active color set by escape sequences.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and the value(-1, -1, -1)is returned without inquiry.- Parameters:
- Return type:
- Returns:
background color as tuple in form of
(r, g, b). When a timeout is specified, always ensure the return value is checked for(-1, -1, -1).- Raises:
ValueError – If bits is not 8 or 16.
The background color is determined by emitting an OSC 11 color query.
See also
get_fgcolor()for querying the foreground color.Note
The default return value is 16-bit, matching the XParseColor specification of the underlying protocol. For most uses, 8-bit values are preferred:
rgb = term.get_bgcolor(bits=8) term.on_color_rgb(*rgb) # reset background to default
- get_fgcolor_hex(timeout: float = 1.0, maybe_short: bool = False) str[source]
Return default foreground color as hex string.
- Parameters:
- Returns:
Hex color string (
#RRGGBBor#RGB), or empty string on timeout or whenis_a_ttyis False.
Convenience wrapper combining
get_fgcolor()andrgb_to_hex().
- get_bgcolor_hex(timeout: float = 1.0, maybe_short: bool = False) str[source]
Return default background color as hex string.
- Parameters:
- Returns:
Hex color string (
#RRGGBBor#RGB), or empty string on timeout or whenis_a_ttyis False.
Convenience wrapper combining
get_bgcolor()andrgb_to_hex().
- get_device_attributes(timeout: float | None = 1.0, force: bool = False) DeviceAttribute | None[source]
Query the terminal’s Device Attributes (DA1).
When
is_a_ttyis False, no sequences are transmitted or response awaited, andNoneis returned without inquiry.If a Device Attributes query fails to respond within the
timeoutspecified,Noneis returned. If this was the first query for device attributes, all subsequent queries returnNoneunlessforce=Trueis set (sticky failure).Responses are cached indefinitely unless
force=Trueis specified.Note
A
timeoutvalue should be set to avoid blocking when the terminal does not respond to DA1 queries, which may happen with some kinds of “dumb” terminals.- Parameters:
- Return type:
DeviceAttribute or None
- Returns:
DeviceAttribute instance with terminal capabilities, or None if unsupported/timeout
term = Terminal() # Query device attributes da = term.get_device_attributes(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS) if da is not None: print(f"Service class: {da.service_class}") print(f"Supports sixel: {da.supports_sixel}") print(f"Extensions: {sorted(da.extensions)}")
- get_software_version(timeout: float | None = 1.0, force: bool = False) SoftwareVersion | None[source]
Query the terminal’s software name and version using XTVERSION.
Sends an XTVERSION query to the terminal and returns a
SoftwareVersioninstance with the terminal’s name and version.If an XTVERSION query fails to respond within the
timeoutspecified, falls back to theTERM_PROGRAMandTERM_PROGRAM_VERSIONenvironment variables. ReturnsNoneonly if both methods fail.Successful responses are cached indefinitely unless
force=Trueis specified. Unlike other query methods, there is no sticky failure mechanism - each failed query can be retried.Note
A
timeoutvalue should be set to avoid blocking when the terminal does not respond to XTVERSION queries, which may happen with some kinds of “dumb” terminals.- Parameters:
- Return type:
SoftwareVersion or None
- Returns:
SoftwareVersion instance with terminal name and version, or None if unsupported/timeout
term = Terminal() # Query software version sv = term.get_software_version(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS) if sv is not None: print(f"Terminal: {sv.name} {sv.version}")
- does_sixel(timeout: float | None = 1.0, force: bool = False) bool[source]
Query whether the terminal supports sixel graphics.
Sixel is a bitmap graphics format supported by some modern terminal emulators, allowing applications to display inline images.
When
is_a_ttyis False, no sequences are transmitted or response awaited, andFalseis returned without inquiry.This method calls
get_device_attributes()to query the terminal’s capabilities and checks for sixel support (extension 4 in the DA1 response). Results are cached, so subsequent calls are fast.
- detect_ambiguous_width(timeout: float = 1.0, fallback: int = 1) int[source]
Detect whether terminal renders ambiguous width characters as width 1 or 2.
East Asian ambiguous width characters can be rendered as either single (1) or double width (2), depending on terminal settings. This method measures the actual rendered width by printing a test character and querying the cursor position. The character is drawn and erased at the current cursor position. The test character used is U+00A7 (SECTION SIGN), an early Unicode character with East Asian Width property “Ambiguous”.
When
is_a_ttyis False, no sequences are transmitted or response awaited, andfallbackis returned without inquiry.- Parameters:
- Return type:
- Returns:
1 for “Ambiguous width as narrow”, 2 is “Ambiguous width as wide”
Example usage:
>>> term = Terminal() >>> width = term.detect_ambiguous_width() >>> if width == 2: ... # Terminal uses double-width for ambiguous characters ... pass
- get_dec_mode(mode: int | DecPrivateMode, timeout: float = 1.0, force: bool = False) DecModeResponse[source]
Query the state of a DEC Private Mode (DECRQM).
Sends a DECRQM query to the terminal and returns a
DecModeResponseinstance. Use the helper methods likeDecModeResponse.is_supported()orDecModeResponse.is_enabled()and others to interpret the result.When
is_a_ttyis False, no sequences are transmitted or response awaited, and theDecModeResponsevalue returned is alwaysDecModeResponse.NOT_QUERIED.In some cases a
timeoutvalue should be set, as it is possible for a terminal that succeedsis_a_ttyto fail to respond to DEC Private Modes, such as in a CI Build Service or other “dumb” terminal, even a few popular modern ones such as Konsole.If a DEC Private mode query fails to respond within the
timeoutspecified, theDecModeResponsevalue returned isDecModeResponse.NO_RESPONSE. If this was the first DEC Private mode query, all subsequent queries return aDecModeResponsevalue ofDecModeResponse.NOT_QUERIEDunlessforce=Trueis set.Repeat queries return the (cached) known state immediately without re-inquiry unless
force=True. Although there are special cases where a user may re-configure their terminal settings after the state was requested by an application, the application is generally restarted to recognize the new settings rather than to repeatedly re-inquire about their latest value!- Parameters:
- Return type:
- Returns:
DecModeResponse instance
- Raises:
TypeError – If mode is not DecPrivateMode or int
term = Terminal() # Query synchronized output support response = term.get_dec_mode(DecPrivateMode.SYNCHRONIZED_OUTPUT) if response.supported: print("Synchronized output is available")
- dec_modes_enabled(*modes: int | DecPrivateMode, timeout: float | None = 1.0) Generator[None, None, None][source]
Context manager for temporarily enabling DEC Private Modes.
On entry, queries each mode’s current state using get_dec_mode().
For modes that are supported but currently disabled, enables them and tracks them for restoration. On exit, disables all modes that were enabled by this context manager, restoring original state.
Unsupported modes are silently ignored.
- Parameters:
modes – One or more DEC Private Mode numbers or enum members
timeout (float) – Timeout in seconds for get_dec_mode calls
- Raises:
TypeError – If mode is not DecPrivateMode or int
term = Terminal() # Enable synchronized output temporarily with term.dec_modes_enabled(DecPrivateMode.SYNCHRONIZED_OUTPUT): # All output will be atomic print("Frame 1") print("Frame 2")
- dec_modes_disabled(*modes: int | DecPrivateMode, timeout: float | None = 1.0) Generator[None, None, None][source]
Context manager for temporarily disabling DEC Private Modes.
Uses the same logic as dec_modes_enabled but inverted: disables supported modes that are currently enabled on entry, then restores them on exit.
- does_mouse(*, clicks: bool = True, report_pixels: bool = False, report_drag: bool = False, report_motion: bool = False, timeout: float = 1.0) bool[source]
Check if the terminal supports the specified mouse tracking features.
This method queries terminal support for the same DEC modes that
mouse_enabled()would enable with the given parameters.- Parameters:
- Returns:
True if all required modes are supported
- Return type:
Example:
if term.does_mouse(report_drag=True, report_pixels=True): with term.mouse_enabled(report_drag=True, report_pixels=True): # Use mouse tracking with drag and pixel support pass
- does_inband_resize(timeout: float = 1.0) bool[source]
Check if the terminal supports in-band window resize notifications.
This method queries whether the terminal supports DEC mode 2048 (IN_BAND_WINDOW_RESIZE), which allows receiving resize events as in-band sequences through
inkey()instead of relying on SIGWINCH signals.- Parameters:
timeout (float) – Timeout for mode query (default 1.0s)
- Returns:
True if in-band resize notifications are supported
- Return type:
Example:
if term.does_inband_resize(): with term.notify_on_resize(): # Use in-band resize events pass else: # Fall back to SIGWINCH or other methods pass
- does_bracketed_paste(timeout: float = 1.0) bool[source]
Check if the terminal supports bracketed paste mode.
Bracketed paste mode (DEC mode 2004) wraps pasted text in special sequences so applications can distinguish pasted text from typed input.
- does_synchronized_output(timeout: float = 1.0) bool[source]
Check if the terminal supports synchronized output.
Synchronized output (DEC mode 2026) allows applications to batch screen updates, preventing tearing during rapid redraws.
- does_grapheme_clustering(timeout: float = 1.0) bool[source]
Check if the terminal supports grapheme clustering.
Grapheme clustering (DEC mode 2027) enables Unicode grapheme cluster aware cursor movement and display.
- does_focus_events(timeout: float = 1.0) bool[source]
Check if the terminal supports focus in/out event reporting.
Focus event reporting (DEC mode 1004) sends escape sequences when the terminal window gains or loses focus.
- get_xtgettcap(timeout: float | None = 1.0, force: bool = False, caps: Iterable[str] | None = None) TermcapResponse | None[source]
Query terminal capabilities via XTGETTCAP (DCS +q).
When caps is specified, only those capabilities are returned. When unspecified, all known XTGETTCAP capabilities are queried and returned. All results from XTGETTCAP are memoized permanently, unlike DECRQSS
get_decrqss()which may change. Usingforce=Trueto re-retrieve any request.
- does_xtgettcap(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports XTGETTCAP (DCS +q) queries.
- does_kitty_graphics(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports the Kitty graphics protocol.
Sends a minimal Kitty graphics query and checks for an
OKresponse. Supported by kitty and WezTerm.
- get_iterm2_capabilities(timeout: float | None = 1.0, force: bool = False) ITerm2Capabilities | None[source]
Query iTerm2 capabilities via OSC 1337;Capabilities.
When
is_a_ttyis False, returnsNone.Responses are cached unless force is True.
- Parameters:
- Return type:
ITerm2Capabilities or None
- does_iterm2(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports any iTerm2 protocols.
- does_iterm2_graphics(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports iTerm2 inline image protocol.
This is equivalent to
does_iterm2()and exists to pair withdoes_kitty_graphics()for graphics capability checks.
- does_kitty_notifications(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports Kitty desktop notifications (OSC 99).
Sends an OSC 99 query with a CPR boundary guard for fast negative detection. Currently supported only by kitty.
- does_kitty_clipboard(timeout: float | None = 1.0, force: bool = False) bool[source]
Check if the terminal supports the Kitty clipboard protocol (mode 5522).
Sends a DECRQM query for DEC private mode 5522 (Bracketed Paste MIME) with a CPR boundary guard for fast negative detection on terminals that do not recognize the mode.
- does_kitty_pointer_shapes(timeout: float | None = 1.0, force: bool = False) str | None[source]
Query Kitty mouse pointer shape support (OSC 22).
Returns the current pointer shape name if supported, or
Noneif the terminal does not respond. Uses a CPR boundary guard for fast negative detection.
- does_osc52_clipboard(timeout: float | None = 1.0, force: bool = False) bool[source]
Detect OSC 52 clipboard support without reading the clipboard.
This method uses non-intrusive detection to avoid triggering user-facing clipboard permission prompts, DA1 extension 52 and XTGETTCAP ``Ms`` fields. These methods are preferred over sending an actual OSC 52 read request (
\x1b]52;c;?\a), which may trigger a clipboard permission dialog in many modern terminals.
- clipboard_copy(text: str, selection: str = 'c') None[source]
Copy text to the system clipboard via OSC 52.
Writes an OSC 52 set sequence to the terminal output stream. Most modern terminals accept clipboard writes without any user prompt.
The sequence is written unconditionally when
does_stylingisTrue. If the terminal does not support OSC 52, the sequence should be ignored by the terminal.
- clipboard_paste(timeout: float | None = 10, selection: str = 'c') str | None[source]
Read the system clipboard via OSC 52.
Sends an OSC 52 query (
\x1b]52;c;?\a) and waits for the terminal to respond with the clipboard contents.Warning
Many modern terminals display a permission dialog when an application reads the clipboard. The user must approve the dialog before the terminal sends a response.
The default timeout of 10 seconds allows time for human interaction. If the user denies the dialog, or no response is received within given timeout, this method returns
None.- Parameters:
- Return type:
str or None
- Returns:
The clipboard text, or
Noneif denied or timeout is reached.
- get_color_scheme(timeout: float | None = 1.0, force: bool = False) str | None[source]
Query the terminal’s color scheme preference (dark or light mode).
Sends a
CSI ? 996 nDevice Status Report query. Terminals that support color-scheme reporting respond withCSI ? 997 ; Ps nwhere Ps is1for dark mode or2for light mode. Uses a CPR boundary guard for fast negative detection.This relates to Mode 2031 (
COLOR_PALETTE_UPDATES) (not implemented).See also
- does_kitty_query(timeout: float | None = 1.0, force: bool = False) bool[source]
Detect Kitty with XTGETTCAP query extensions.
This is a trifle convenience wrapper of
get_xtgettcap().This method probes for
kitty-query-namesupport. A successful response indicates that some set of Kitty query extensions are available.To retrieve their values, follow up with
get_xtgettcap()directly, for example:>>> term = Terminal() >>> term.does_kitty_query() True >>> term.get_xtgettcap(caps=[f"kitty-query-{key}" for key in [ "font_family", "font_size", "dpi_x", "dpi_y"]]) TermcapResponse(supported=True, capabilities={ 'kitty-query-font_family': 'NotoSansMono-Regular', 'kitty-query-font_size': '19', 'kitty-query-dpi_x': '96', 'kitty-query-dpi_y': '96'})
- get_decrqss(setting_id: str = 'm', timeout: float | None = 1.0) str | None[source]
Query terminal state via DECRQSS (Request Status String).
Sends
DCS $ q <setting_id> STand decodes the response. Returns the parameter value string on success, with the echoed setting identifier stripped. ReturnsNonewhen the terminal does not support DECRQSS or the setting is invalid.Results are not cached – DECRQSS queries runtime state that may change between calls (cursor style, margins, SGR, etc.).
Use
Decrqssfor setting identifiers:term = Terminal() term.get_decrqss(term.Decrqss.DECSCUSR) # cursor style term.get_decrqss(term.Decrqss.DECSTBM) # scroll region
See also
- does_decrqss(timeout: float | None = 1.0, force: bool = False) bool[source]
Detect DECRQSS (Request Status String) support.
Sends a
DECRQSSquery for the current SGR state. A valid response indicates the terminal supports status string queries.See also
- does_styled_underlines(timeout: float | None = 1.0, force: bool = False) bool[source]
Detect extended underline style support (curly, dotted, dashed).
Queries the terminal’s
Smulxterminfo capability via XTGETTCAP. When supported, the terminal can render underline styles beyond the standard single underline, such asCSI 4:3 m(curly).
- does_colored_underlines(timeout: float | None = 1.0, force: bool = False) bool[source]
Detect colored underline support (
CSI 58;2;r;g;b m).Queries the terminal’s
Setulcterminfo capability via XTGETTCAP.
- does_text_sizing(timeout: float = 1.0, force: bool = False) TextSizingResult[source]
Detect Kitty text sizing protocol support (OSC 66).
Tests width and scale text sizing by sending OSC 66 probes and measuring cursor position delta. Supported terminals may write up to 2 destructive spaces at the current cursor position, while unsupported terminals typically produce no output.
Responses are cached unless force is True.
- mouse_enabled(*, clicks: bool = True, report_pixels: bool = False, report_drag: bool = False, report_motion: bool = False, timeout: float = 1.0) Generator[None, None, None][source]
Context manager for enabling mouse tracking with various reporting modes.
Enables mouse event reporting with sensible defaults, and always enables SGR extended mouse mode (1006).
- Parameters:
clicks (bool) – Enable basic click reporting (default True)
report_pixels (bool) – Report pixel coordinates instead of cell coordinates
report_drag (bool) – Report mouse drag events (button held while moving)
report_motion (bool) – Report all mouse motion events
timeout (float) – Timeout for mode queries (default 1.0s)
The reporting modes have precedence: motion > drag > clicks. Enabling a higher-precedence mode automatically includes lower modes.
Example:
with term.mouse_enabled(): # Basic click tracking inp = term.inkey() if inp.name and inp.name.startswith('MOUSE_'): print(f"Clicked at {inp.x}, {inp.y}") with term.mouse_enabled(report_drag=True): # Track clicks and drags pass with term.mouse_enabled(report_motion=True, report_pixels=True): # Track all motion with pixel coordinates pass
- bracketed_paste(timeout: float = 1.0) Generator[None, None, None][source]
Context manager for enabling bracketed paste mode.
When enabled, pasted text is wrapped with special escape sequences, allowing applications to distinguish pasted content from typed input.
- Parameters:
timeout (float) – Timeout for mode query (default 1.0s)
Example:
with term.bracketed_paste(): inp = term.inkey() if inp.name == 'BRACKETED_PASTE': pasted_text = inp.text print(f"You pasted: {pasted_text}")
- synchronized_output(timeout: float = 1.0) Generator[None, None, None][source]
Context manager for enabling synchronized output mode.
Buffers all terminal output until the context exits, eliminating screen flicker during redraws. Perfect for animations and full-screen updates.
- Parameters:
timeout (float) – Timeout for mode query (default 1.0s)
- focus_events(timeout: float = 1.0) Generator[None, None, None][source]
Context manager for enabling focus event reporting.
Reports when the terminal window gains or loses focus, useful for pausing animations or updating status indicators.
- Parameters:
timeout (float) – Timeout for mode query (default 1.0s)
- notify_on_resize(timeout: float = 1.0) Generator[None, None, None][source]
Context manager for enabling in-band window resize notifications.
When enabled, the terminal will automatically send resize events as in-band sequences whenever the window size changes. These events are received by
inkey()as keystroke events withnameequal to'RESIZE_EVENT'.The new dimensions are automatically cached and available immediately through the standard
height,width,pixel_height, andpixel_widthproperties without additional ioctl system calls.This is the preferred method for handling terminal resizes as it avoids the race conditions and signal handling complexity of SIGWINCH on Unix systems, and provides a consistent cross-platform API.
- Parameters:
timeout (float) – Timeout for mode query (default 1.0s)
Example:
with term.notify_on_resize(): while True: inp = term.inkey(timeout=0.1) if inp.name == 'RESIZE_EVENT': # Dimensions updated automatically redraw_display(term.height, term.width) elif inp == 'q': break
- get_sixel_height_and_width(timeout: float | None = 1.0, force: bool = False) Tuple[int, int][source]
Query sixel graphics pixel dimensions.
Returns the maximum height and width in pixels for sixel graphics rendering. Detection order (from most to least reliable):
XTWINOPS 16t (CSI 16 t) - Character cell size, multiplied by rows/cols
XTWINOPS 14t (CSI 14 t) - Text area size in pixels
XTSMGRAPHICS - Sixel graphics query
TIOCSWINSZ / In-band resize - System ioctl / event pixel dimensions
The cell-based calculation (method 1) is preferred because it accounts for the actual drawable text area, excluding window margins and decorations.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and(-1, -1)is returned without inquiry.
- get_sixel_colors(timeout: float | None = 1.0, force: bool = False) int[source]
Query number of sixel color registers (XTSMGRAPHICS).
Returns the maximum number of color registers available for sixel graphics rendering. If XTSMGRAPHICS query fails but the terminal advertises Sixel support via DA1 (Device Attributes), returns 256 as a sensible default.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and-1is returned without inquiry.
- get_cell_height_and_width(timeout: float | None = 1.0, force: bool = False) Tuple[int, int][source]
Query character cell pixel dimensions (XTWINOPS).
Returns the height and width in pixels of a single character cell.
When
is_a_ttyis False, no sequences are transmitted or response awaited, and(-1, -1)is returned without inquiry.
- get_kitty_keyboard_state(timeout: float | None = 1.0, force: bool = False) KittyKeyboardProtocol | None[source]
Query the current Kitty keyboard protocol flags.
Sends a Kitty keyboard protocol query to the terminal and returns a
KittyKeyboardProtocolinstance with the current flags. This method is not normally used directly, rather it is used by theenable_kitty_keyboard()context manager on entrance to discover and restore the previous state on exit.When
is_a_ttyis False, no sequences are transmitted or response awaited, andNoneis returned.In many cases a
timeoutvalue (in seconds) should be set, as it is possible for a terminal that succeedsis_a_ttyto fail to respond to either Kitty keyboard protocol state request, or the simple device attribute request query carried with it! And not just “dumb” terminals fail to respond, even some fairly modern terminals like Konsole.If a Kitty keyboard protocol query fails to respond within the
timeoutspecified,Noneis returned. If this was the first Kitty keyboard protocol query, all subsequent queries returnNoneunlessforce=Trueis set.No state caching is performed - each call re-queries the terminal unless the first query previously failed (sticky failure) and
force=False.- Parameters:
- Return type:
KittyKeyboardProtocol or None
- Returns:
KittyKeyboardProtocol instance with current flags, or None if unsupported/timeout
- enable_kitty_keyboard(*, disambiguate: bool = True, report_events: bool = False, report_alternates: bool = False, report_all_keys: bool = False, report_text: bool = False, mode: int = 1, timeout: float | None = 1.0, force: bool = False) Generator[None, None, None][source]
Context manager that enables Kitty keyboard protocol features.
- Parameters:
disambiguate (bool) – Enable disambiguated escape codes (fixes issues with Esc vs sequences)
report_events (bool) – Report key repeat and release events
report_alternates (bool) – Report shifted and base layout keys for shortcuts
report_all_keys (bool) – Report all keys as escape codes (including text keys)
report_text (bool) – Report associated text with key events (requires report_all_keys)
mode (int) – Protocol mode (1=set/clear specified flags, 2=set only, 3=clear only)
timeout (float) – Timeout for querying current flags before setting new ones
force (bool) – Force sequences to be emitted even if timeout previously occurred
Always queries current state before setting new flags and restores previous state on exit.
Example:
with term.enable_kitty_keyboard(disambiguate=True): # Now Alt+C won't conflict with Ctrl+C key = term.inkey() if key.alt and key.is_alt('c'): print("Alt+C pressed")
Note
A
timeoutvalue should be set to avoid blocking when the terminal does not respond to DA1 or kitty protocol queries, which may happen with some kinds of “dumb” terminals, even some modern terminals like Konsole.
- fullscreen() Generator[None, None, None][source]
Context manager that switches to secondary screen, restoring on exit.
Under the hood, this switches between the primary screen buffer and the secondary one. The primary one is saved on entry and restored on exit. Likewise, the secondary contents are also stable and are faithfully restored on the next entry:
with term.fullscreen(): main()
Note
There is only one primary and one secondary screen buffer.
fullscreen()calls cannot be nested, only one should be entered at a time.
Context manager that hides the cursor, setting visibility on exit.
- with term.hidden_cursor():
main()
Note
hidden_cursor()calls cannot be nested: only one should be entered at a time.
- cursor_shape(style: int | str = 2) Generator[None, None, None][source]
Context manager that sets cursor shape, restoring default on exit.
- Parameters:
style – A
CursorShapeconstant or string name (e.g.'blinking_bar').
Uses DECSCUSR (DEC Set Cursor Style) escape sequences:
with term.cursor_shape(term.CursorShape.BLINKING_BAR): main()
String names are also accepted:
with term.cursor_shape('steady_underline'): main()
On exit, the cursor is reset to the terminal default (DECSCUSR 0).
Note
DECSCUSR is supported by most modern terminals including xterm, VTE-based terminals, iTerm2, Windows Terminal, kitty, ghostty, alacritty, and WezTerm.
- no_line_wrap() Generator[None, None, None][source]
Context manager that disables line wrapping, enabling on exit.
Uses DEC Auto Wrap Mode (DECAWM) to control whether text reaching the right edge wraps to the next line:
with term.no_line_wrap(): print(term.move_x(0) + 'x' * 200) # Clips, doesn't wrap
On exit, line wrapping is unconditionally enabled as terminals should prefer line-wrapping mode for normal operation.
Note
no_line_wrap()calls cannot be nested: only one should be entered at a time.
- scroll_region(top: int = 0, height: int | None = None) Generator[None, None, None][source]
Context manager that sets a scrolling region, resetting on exit.
- Parameters:
- Returns:
a context manager.
- Return type:
Iterator
A scrolling region restricts scrolling to a portion of the screen. When text scrolls within the region, content outside the region remains fixed. This is useful for creating interfaces with fixed headers, footers, or status bars:
with term.fullscreen(), term.scroll_region(top=1, height=term.height - 2): # row 0 and the last row remain fixed # scrolling happens only in the middle region for i in range(100): print(f'Line {i}')
The cursor position may be reset to the home position when the scroll region changes. Use
move_yx()to reposition as needed after entering the context.Note
scroll_region()calls cannot be nested: only one should be entered at a time.
- move_xy(x: int, y: int) str[source]
A callable string that moves the cursor to the given
(x, y)screen coordinates.- Parameters:
- Return type:
- Returns:
Callable string that moves the cursor to the given coordinates
- move_yx(y: int, x: int) str[source]
A callable string that moves the cursor to the given
(y, x)screen coordinates.- Parameters:
- Return type:
- Returns:
Callable string that moves the cursor to the given coordinates
- property move_left: FormattingOtherString
Move cursor 1 cells to the left, or callable string for n>1 cells.
- property move_right: FormattingOtherString
Move cursor 1 or more cells to the right, or callable string for n>1 cells.
- property move_up: FormattingOtherString
Move cursor 1 or more cells upwards, or callable string for n>1 cells.
- property move_down: FormattingOtherString
Move cursor 1 or more cells downwards, or callable string for n>1 cells.
- property color: NullCallableString | ParameterizingString
A callable string that sets the foreground color.
- Return type:
The capability is unparameterized until called and passed a number, at which point it returns another string which represents a specific color change. This second string can further be called to color a piece of text and set everything back to normal afterward.
This should not be used directly, but rather a specific color by name or
color_rgb()value.
- color_rgb(red: int, green: int, blue: int) FormattingString[source]
Provides callable formatting string to set foreground color to the specified RGB color.
- Parameters:
- Return type:
- Returns:
Callable string that sets the foreground color.
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm.
- color_hex(hex_color: str) FormattingString[source]
Provides callable formatting string to set foreground color from hex.
- Parameters:
hex_color (str) – Hex color in
#RGB,#RRGGBB, or#RRRRGGGGBBBBformat. The#prefix is optional.- Return type:
- Returns:
Callable string that sets the foreground color.
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm.See
hex_to_rgb()for supported hex formats.
- property on_color: NullCallableString | ParameterizingString
A callable capability that sets the background color.
- Return type:
- on_color_rgb(red: int, green: int, blue: int) FormattingString[source]
Provides callable formatting string to set background color to the specified RGB color.
- Parameters:
- Return type:
- Returns:
Callable string that sets the background color.
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm.
- on_color_hex(hex_color: str) FormattingString[source]
Provides callable formatting string to set background color from hex.
- Parameters:
hex_color (str) – Hex color in
#RGB,#RRGGBB, or#RRRRGGGGBBBBformat. The#prefix is optional.- Return type:
- Returns:
Callable string that sets the background color.
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm.See
hex_to_rgb()for supported hex formats.
- formatter(value: str) NullCallableString | FormattingString[source]
Provides callable formatting string to set color and other text formatting options.
- Parameters:
value (str) – Sugary, ordinary, or compound formatted terminal capability, such as “red_on_white”, “normal”, “red”, or “bold_on_black”.
- Return type:
FormattingStringorNullCallableString- Returns:
Callable string that sets color and other text formatting options
Calling
term.formatter('bold_on_red')is equivalent toterm.bold_on_red, but a string that is not a valid text formatter will return aNullCallableString. This is intended to allow validation of text formatters without the possibility of inadvertently returning another terminal capability.
- rgb_downconvert(red: int, green: int, blue: int) int[source]
Translate an RGB color to a color code of the terminal’s color depth.
This method is only be used to downconvert for terminals of 256 or fewer colors.
- property normal: str
A capability that resets all video attributes.
- Return type:
normalis an alias forsgr0orexit_attribute_mode. Any styling attributes previously applied, such as foreground or background colors, reverse video, or bold are reset to defaults.
- link(url: str, text: str, url_id: str = '') str[source]
Display
textthat when touched or clicked, navigates tourl.Optional
url_idmay be specified, so that non-adjacent cells can reference a single target, all cells painted with the same “id” will highlight on hover, rather than any individual one, as described in “Hovering and underlining the id parameter” of gist https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
- set_window_title(title: str, mode: int = 0) str[source]
Return sequence to set the terminal title.
Uses xterm OSC (Operating System Command) sequences to set the window and/or icon title.
- Parameters:
- Return type:
- Returns:
Escape sequence string that sets the terminal title, or empty string when
does_stylingisFalse.
- window_title(title: str, mode: int = 0) Generator[None, None, None][source]
Context manager that sets terminal title, restoring on exit.
Uses the xterm title stack (XTWINOPS push/pop) to save and restore the previous title. Not all terminals support the title stack – those that do not will simply set the title without restoring it on exit.
- progress_bar(state: str | int, value: int | None = None) str[source]
Return OSC 9;4 sequence for terminal progress bar support.
Support for ‘OSC 9;4’ cannot be detected. It is generally safe to write to unsupported terminals. Some terminals display a graphical progress indicator in the taskbar and window menu or status bar matching the given value (0-100). Supported by at least Windows Terminal.exe, ConEmu, Ghostty, kitty, and iTerm2.
- Parameters:
state¶ –
Progress state. Accepts either an integer or a string name:
0or'clear': Remove progress indicator1or'normal': Set progress to value (0 to 100)2or'error': Error state (typically red)3or'indeterminate': Indeterminate / pulsing4or'paused': Paused state (typically yellow)
value¶ (int) – Progress value as integer of percent (0 to 100). Required when state is
'normal'or1. Terminals are expected to ignore ‘value’ for all other states.
- Return type:
- Returns:
OSC 9;4 escape sequence, or
''whendoes_stylingisFalse.- Raises:
ValueError – on bad
stateidentifier or invalid or out of boundsvalue.
- property stream: IO[str]
Read-only property: stream the terminal outputs to.
This is a convenience attribute. It is used internally for implied writes performed by context managers
hidden_cursor(),fullscreen(),location(), andkeypad().
- property number_of_colors: int
Number of colors supported by terminal.
Common return values are 0, 8, 16, 256, or 1 << 24.
This may be used to test whether the terminal supports colors, and at what depth, if that’s a concern.
If this property is assigned a value of 88, the value 16 will be saved. This is due to the the rarity of 88 color support and the inconsistency of behavior between implementations.
Assigning this property to a value other than 0, 4, 8, 16, 88, 256, or 1 << 24 will raise an
AssertionError.
- property color_distance_algorithm: str
Color distance algorithm used by
rgb_downconvert().The slowest, but most accurate, ‘cie2000’, is default. Other available options are ‘rgb’, ‘rgb-weighted’, ‘cie76’, and ‘cie94’. This function is only be used to downconvert for terminals of 256 or fewer colors.
- ljust(text: str, width: SupportsIndex | None = None, fillchar: str = ' ') str[source]
Left-align
text, which may contain terminal sequences.
- rjust(text: str, width: SupportsIndex | None = None, fillchar: str = ' ') str[source]
Right-align
text, which may contain terminal sequences.
- center(text: str, width: SupportsIndex | None = None, fillchar: str = ' ') str[source]
Center
text, which may contain terminal sequences.
- text_sized(text: str, scale: int = 1, *, width: int = 0, numerator: int = 0, denominator: int = 0, vertical_align: int | str = 0, horizontal_align: int | str = 0) str[source]
Wrap
textin a text sizing escape sequence (OSC 66).Returns
textunchanged when the terminal does not support text sizing, providing graceful degradation.- Parameters:
text (str) – Text payload.
scale (int) – Scale factor (1 to 7).
width (int) – Width in cells (0 to 7). 0 means auto-calculate from the inner text.
numerator (int) – Fractional scaling numerator (0 to 15).
denominator (int) – Fractional scaling denominator (0 to 15).
vertical_align – Vertical alignment: (‘top’, ‘bottom’, ‘center’), or protocol code (0=top, 1=bottom, 2=center).
horizontal_align – Horizontal alignment. (‘left’, ‘right’, ‘center’) or protocol code (0=left, 1=right, 2=center).
- Return type:
- Returns:
Text wrapped in an OSC 66 escape sequence, or plain
texton unsupported terminals.- Raises:
ValueError – when the encoded
textexceeds 4096 bytes.ValueError – when
vertical_alignorhorizontal_alignis an unrecognized string value.
See also
Note
Because the first call to
Terminal.text_sized()will cause the side effect of writing destructive spaces to the columns and row following the current cursor position as required for detection of kitty text sizing protocol, it is suggested to first callTerminal.does_text_sizing()during program initialization.The result is permanently cached and all further calls to these methods return immediately without this side effect.
- truncate(text: str, width: SupportsIndex | None = None) str[source]
Truncate
texttowidthprintable characters, retaining terminal sequences.Wide characters (such as CJK or emoji) that would partially exceed
widthare replaced with space padding to maintain exact width.- Parameters:
- Return type:
- Returns:
texttruncated to exactlywidthprintable characters
>>> term.truncate('xyz\x1b[0;3m', 2) 'xy\x1b[0;3m'
- length(text: str) int[source]
Return printable length of a string containing sequences.
Returns the maximum horizontal cursor extent reached while processing the string. Backspace and cursor-left movements do not reduce the length below the maximum position reached.
- Parameters:
text (str) – String to measure. May contain terminal sequences.
- Return type:
- Returns:
The maximum terminal character cell position reached
Wide characters that consume 2 character cells are supported:
>>> term = Terminal() >>> term.length(term.clear + term.red('コンニチハ')) 10
Note
Sequences such as ‘clear’, which is considered as a “movement sequence” because it would move the cursor to (y, x)(0, 0), are evaluated as a printable length of 0.
- strip(text: str, chars: str | None = None) str[source]
Return
textwithout sequences and leading or trailing whitespace.- Return type:
- Returns:
Text with leading and trailing whitespace removed
>>> term.strip(' \x1b[0;3m xyz ') 'xyz'
- rstrip(text: str, chars: str | None = None) str[source]
Return
textwithout terminal sequences or trailing whitespace.- Return type:
- Returns:
Text with terminal sequences and trailing whitespace removed
>>> term.rstrip(' \x1b[0;3m xyz ') ' xyz'
- lstrip(text: str, chars: str | None = None) str[source]
Return
textwithout terminal sequences or leading whitespace.- Return type:
- Returns:
Text with terminal sequences and leading whitespace removed
>>> term.lstrip(' \x1b[0;3m xyz ') 'xyz '
- strip_seqs(text: str) str[source]
Return
textstripped of only its terminal sequences.- Return type:
- Returns:
Text with terminal sequences removed
>>> term.strip_seqs('\x1b[0;3mxyz') 'xyz' >>> term.strip_seqs(term.cuf(5) + term.red('test')) ' test'
Note
Non-destructive sequences that adjust horizontal distance (such as
\borterm.cuf(5)) are replaced by destructive space or erasing.
- split_seqs(text: str, maxsplit: int = 0) List[str][source]
Return
textsplit by individual character elements and sequences.- Parameters:
text (str) – String containing sequences
maxsplit (int) – When maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list (same meaning is argument for
re.split()).
- Return type:
- Returns:
List of sequences and individual characters
>>> term.split_seqs(term.underline('xyz')) ['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
>>> term.split_seqs(term.underline('xyz'), 1) ['\x1b[4m', r'xyz\x1b(B\x1b[m']
- wrap(text: str, width: int | None = None, **kwargs: object) List[str][source]
Text-wrap a string, returning a list of wrapped lines.
- Parameters:
text (str) – Unlike
textwrap.wrap(),textmay contain terminal sequences, such as colors, bold, or underline. By default, tabs intextare expanded bystring.expandtabs().width (int) – Unlike
textwrap.wrap(),widthwill default to the width of the attached terminal.**kwargs – See
textwrap.TextWrapper
- Return type:
- Returns:
List of wrapped lines
- Raises:
ValueError – for non-positive values of
width.
See
textwrap.TextWrapperfor keyword arguments that can customize wrapping behaviour.
- getch(decode_latin1: bool = False) str[source]
Read, decode, and return the next byte from the keyboard stream.
- Parameters:
decode_latin1 (bool) – If True, decode byte as latin-1 (for legacy mouse sequences with 8-bit coordinates).
- Return type:
unicode
- Returns:
a single unicode character, or
''if a multi-byte sequence has not yet been fully received.- Raises:
EOFError – When the keyboard stream has reached end-of-file.
This method name and behavior mimics curses
getch(void), and it supportsinkey(), reading only one byte from the keyboard string at a time. This method should always return without blocking if called afterkbhit()has returned True.Implementers of alternate input stream methods should override this method.
- ungetch(text: str) None[source]
Buffer input data to be discovered by next call to
inkey().- Parameters:
text (str) – String to be buffered as keyboard input.
- kbhit(timeout: float | None = None) bool[source]
Return whether a keypress has been detected on the keyboard.
This method is used by
inkey()to determine if a byte may be read usinggetch()without blocking. The standard implementation simply uses theselect.select()call on stdin.- Parameters:
timeout (float) – When
timeoutis 0, this call is non-blocking, otherwise blocking indefinitely until keypress is detected when None (default). Whentimeoutis a positive number, returns aftertimeoutseconds have elapsed (float).- Return type:
- Returns:
True if a keypress is awaiting to be read on the keyboard attached to this terminal. When input is not a terminal, False is always returned.
- cbreak() Generator[None, None, None][source]
Allow each keystroke to be read immediately after it is pressed.
This is a context manager for
tty.setcbreak().This context manager activates ‘rare’ mode, the opposite of ‘cooked’ mode: On entry,
tty.setcbreak()mode is activated disabling line-buffering of keyboard input and turning off automatic echo of input as output.Note
You must explicitly print any user input you would like displayed. If you provide any kind of editing, you must handle backspace and other line-editing control functions in this mode as well!
Normally, characters received from the keyboard cannot be read by Python until the Return key is pressed. Also known as cooked or canonical input mode, it allows the tty driver to provide line-editing before shuttling the input to your program and is the (implicit) default terminal mode set by most unix shells before executing programs.
Technically, this context manager sets the
termiosattributes of the terminal attached tosys.__stdin__.Note
tty.setcbreak()setsVMIN = 1andVTIME = 0, see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
- raw() Generator[None, None, None][source]
A context manager for
tty.setraw().Although both
cbreak()andraw()modes allow each keystroke to be read immediately after it is pressed, Raw mode disables processing of input and output by the terminal driver.In cbreak mode, special input characters such as
^Cor^Sare interpreted by the terminal driver and excluded from the stdin stream. In raw mode these values are received by theinkey()method.Because output processing is not done by the terminal driver, the newline
'\n'is not enough, you must also print carriage return to ensure that the cursor is returned to the first column:with term.raw(): print("printing in raw mode", end="\r\n")
- keypad() Generator[None, None, None][source]
Context manager that enables directional keypad input.
On entry, this puts the terminal into “keyboard_transmit” mode by emitting the keypad_xmit (smkx) capability. On exit, it emits keypad_local (rmkx).
On an IBM-PC keyboard with numeric keypad of terminal-type xterm, with numlock off, the lower-left diagonal key transmits sequence
\\x1b[F, translated toTerminalattributeKEY_END.However, upon entering
keypad(),\\x1b[OFis transmitted, translating toKEY_LL(lower-left key), allowing you to determine diagonal direction keys.
- flushinp(timeout: float = 0) str[source]
Unbuffer and return all input available within
timeout.When legacy mouse sequence
'\x1b[M'is detected in input stream, all remaining bytes are decoded as latin1 to handle 8-bit coordinates.
- inkey(timeout: float | None = None, esc_delay: float = 0.35, capture_cpr: bool = False) Keystroke[source]
Read and return the next keyboard event within given timeout.
Generally, this should be used inside the
raw()orcbreak()context manager.- Parameters:
timeout (float) – Number of seconds to wait for a keystroke before returning. When
None(default), this method may block indefinitely.esc_delay (float) –
Time in seconds to block after Escape key is received to await another key sequence beginning with escape such as KEY_LEFT, sequence
'\x1b[D', before returning aKeystrokeinstance forKEY_ESCAPE.Users may override the default value of
esc_delayin seconds, using environment value ofESCDELAYas milliseconds, see ncurses(3) section labeled ESCDELAY for details. Setting the value as an argument to this function will override any such preference.capture_cpr (bool) – Prefer matches of
CPR_RESPONSEover conflicting vt220 Legacy function keys (eg.KEY_F3,KEY_SHIFT_F3).
- Return type:
- Returns:
Keystroke, which may be empty ('') iftimeoutis specified and keystroke is not received.
Note
When used without the context manager
cbreak(), orraw(),sys.__stdin__remains line-buffered, and this function will block until the return key is pressed!Note
On Windows, a 10 ms sleep is added to the key press detection loop to reduce CPU load. Due to the behavior of
time.sleep()on Windows, this will actually result in a 15.6 ms delay when using the default time resolution. Decreasing the time resolution will reduce this to 10 ms, while increasing it, which is rarely done, will have a perceptable impact on the behavior.ncurses(3): https://www.man7.org/linux/man-pages/man3/ncurses.3x.html
- async async_inkey(timeout: float | None = None, esc_delay: float = 0.35, capture_cpr: bool = False) Keystroke[source]
Asynchronous version of
inkey()for use withasyncio.Read and return the next keyboard event within given timeout, yielding control to the asyncio event loop while waiting for input rather than blocking the thread.
Uses
asyncio.AbstractEventLoop.add_reader()on the keyboard file descriptor, reusing the sameresolve_sequence(), keymap, andKeystrokeinternals as the synchronousinkey().Must be called within a
cbreak()orraw()context, just likeinkey().- Parameters:
timeout (float) – Number of seconds to wait for a keystroke before returning. When
None(default), this method may block indefinitely.esc_delay (float) – Time in seconds to wait after Escape key is received to disambiguate bare Escape from escape sequences.
capture_cpr (bool) – Prefer matches of
CPR_RESPONSEover conflicting vt220 Legacy function keys (eg.KEY_F3,KEY_SHIFT_F3).
- Return type:
- Returns:
Keystroke, which may be empty ('') iftimeoutis specified and keystroke is not received.
- class WINSZ(ws_row, ws_col, ws_xpixel, ws_ypixel)[source]
Structure represents return value of
termios.TIOCGWINSZ.- ws_row
rows, in characters
- ws_col
columns, in characters
- ws_xpixel
horizontal size, pixels
- ws_ypixel
vertical size, pixels
Create new instance of WINSZ(ws_row, ws_col, ws_xpixel, ws_ypixel)