terminal.py
Module containing Terminal
, the primary API entry point.
- class Terminal(kind=None, stream=None, force_styling=False)[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 as taken by
curses.setupterm()
. Defaults to the value of theTERM
environment variable.Note
Terminals within a single process must share a common
kind
. See_CUR_TERM
.stream (file) –
A file-like object representing the Terminal output. Defaults to the original value of
sys.__stdout__
, likecurses.initscr()
does.If
stream
is 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 -r
or build systems which support decoding of terminal sequences.
- __getattr__(attr)[source]
Return a terminal capability as Unicode string.
For example,
term.bold
is 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
Read-only property: Terminal kind determined on class initialization.
- Return type:
- property does_styling
Read-only property: Whether this class instance may emit sequences.
- Return type:
- location(x=None, y=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
x
to move to a certain column,y
to 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 Compaibility with the blessings library, sorry for the trouble!
- get_location(timeout=None)[source]
Return tuple (row, column) of cursor position.
- 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)
. When a timeout is specified, always ensure the return value is checked for(-1, -1)
.
The location of the cursor is determined by emitting the
u7
terminal capability, or VT100 Query Cursor Position when such capability is undefined, which elicits a response from a reply string described by capabilityu6
, or again VT100’s definition of\x1b[%i%d;%dR
when undefined.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=None)[source]
Return tuple (r, g, b) of foreground color.
- Parameters:
timeout (float) – Return after time elapsed in seconds with value
(-1, -1, -1)
indicating that the remote end did not respond.- 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)
.
The foreground color is determined by emitting an OSC 10 color query.
- get_bgcolor(timeout=None)[source]
Return tuple (r, g, b) of background color.
- Parameters:
timeout (float) – Return after time elapsed in seconds with value
(-1, -1, -1)
indicating that the remote end did not respond.- 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)
.
The background color is determined by emitting an OSC 11 color query.
- fullscreen()[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.
- move_xy(x, y)[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, x)[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
Move cursor 1 cells to the left, or callable string for n>1 cells.
- property move_right
Move cursor 1 or more cells to the right, or callable string for n>1 cells.
- property move_up
Move cursor 1 or more cells upwards, or callable string for n>1 cells.
- property move_down
Move cursor 1 or more cells downwards, or callable string for n>1 cells.
- property color
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, green, blue)[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
.
- property on_color
A callable capability that sets the background color.
- Return type:
- on_color_rgb(red, green, blue)[source]
Provides callable formatting string to set background 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
.
- formatter(value)[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:
FormattingString
orNullCallableString
- 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, green, blue)[source]
Translate an RGB color to a color code of the terminal’s color depth.
- property normal
A capability that resets all video attributes.
- Return type:
normal
is an alias forsgr0
orexit_attribute_mode
. Any styling attributes previously applied, such as foreground or background colors, reverse video, or bold are reset to defaults.
- link(url, text, url_id='')[source]
Display
text
that when touched or clicked, navigates tourl
.Optional
url_id
may 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.
- property stream
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
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
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’.
- ljust(text, width=None, fillchar=' ')[source]
Left-align
text
, which may contain terminal sequences.
- rjust(text, width=None, fillchar=' ')[source]
Right-align
text
, which may contain terminal sequences.
- truncate(text, width=None)[source]
Truncate
text
to maximumwidth
printable characters, retaining terminal sequences.- Parameters:
- Return type:
- Returns:
text
truncated to at mostwidth
printable characters
>>> term.truncate(u'xyz\x1b[0;3m', 2) u'xy\x1b[0;3m'
- length(text)[source]
Return printable length of a string containing sequences.
- Parameters:
text (str) – String to measure. May contain terminal sequences.
- Return type:
- Returns:
The number of terminal character cells the string will occupy when printed
Wide characters that consume 2 character cells are supported:
>>> term = Terminal() >>> term.length(term.clear + term.red(u'コンニチハ')) 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, chars=None)[source]
Return
text
without sequences and leading or trailing whitespace.- Return type:
- Returns:
Text with leading and trailing whitespace removed
>>> term.strip(u' \x1b[0;3m xyz ') u'xyz'
- rstrip(text, chars=None)[source]
Return
text
without terminal sequences or trailing whitespace.- Return type:
- Returns:
Text with terminal sequences and trailing whitespace removed
>>> term.rstrip(u' \x1b[0;3m xyz ') u' xyz'
- lstrip(text, chars=None)[source]
Return
text
without terminal sequences or leading whitespace.- Return type:
- Returns:
Text with terminal sequences and leading whitespace removed
>>> term.lstrip(u' \x1b[0;3m xyz ') u'xyz '
- strip_seqs(text)[source]
Return
text
stripped of only its terminal sequences.- Return type:
- Returns:
Text with terminal sequences removed
>>> term.strip_seqs(u'\x1b[0;3mxyz') u'xyz' >>> term.strip_seqs(term.cuf(5) + term.red(u'test')) u' test'
Note
Non-destructive sequences that adjust horizontal distance (such as
\b
orterm.cuf(5)
) are replaced by destructive space or erasing.
- split_seqs(text, maxsplit=0)[source]
Return
text
split 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(u'xyz')) ['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
>>> term.split_seqs(term.underline(u'xyz'), 1) ['\x1b[4m', r'xyz\x1b(B\x1b[m']
- wrap(text, width=None, **kwargs)[source]
Text-wrap a string, returning a list of wrapped lines.
- Parameters:
text (str) – Unlike
textwrap.wrap()
,text
may contain terminal sequences, such as colors, bold, or underline. By default, tabs intext
are expanded bystring.expandtabs()
.width (int) – Unlike
textwrap.wrap()
,width
will default to the width of the attached terminal.**kwargs – See
textwrap.TextWrapper
- Return type:
- Returns:
List of wrapped lines
See
textwrap.TextWrapper
for keyword arguments that can customize wrapping behaviour.
- getch()[source]
Read, decode, and return the next byte from the keyboard stream.
- Return type:
unicode
- Returns:
a single unicode character, or
u''
if a multi-byte sequence has not yet been fully received.
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.Implementors of alternate input stream methods should override this method.
- ungetch(text)[source]
Buffer input data to be discovered by next call to
inkey()
.- Parameters:
text (str) – String to be buffered as keyboard input.
- kbhit(timeout=None)[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
timeout
is 0, this call is non-blocking, otherwise blocking indefinitely until keypress is detected when None (default). Whentimeout
is a positive number, returns aftertimeout
seconds 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()[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
termios
attributes of the terminal attached tosys.__stdin__
.Note
tty.setcbreak()
setsVMIN = 1
andVTIME = 0
, see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
- raw()[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.In cbreak mode, special input characters such as
^C
or^S
are 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, 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()[source]
Context manager that enables directional keypad input.
On entrying, 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 toTerminal
attributeKEY_END
.However, upon entering
keypad()
,\\x1b[OF
is transmitted, translating toKEY_LL
(lower-left key), allowing you to determine diagonal direction keys.
- inkey(timeout=None, esc_delay=0.35)[source]
Read and return the next keyboard event within given timeout.
Generally, this should be used inside the
raw()
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 aKeystroke
instance forKEY_ESCAPE
.Users may override the default value of
esc_delay
in seconds, using environment value ofESCDELAY
as milliseconds, see ncurses(3) section labeled ESCDELAY for details. Setting the value as an argument to this function will override any such preference.
- Return type:
- Returns:
Keystroke
, which may be empty (u''
) iftimeout
is 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
- 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)
- _CUR_TERM = None
The type of the None singleton.