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() and tparm() 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 the TERM environment variable.

    Note

    Terminals withing 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__, like curses.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, use force_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 pairing normal. This capability returns a callable, so you can use term.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 (or cup), 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.

kind

Read-only property: Terminal kind determined on class initialization.

Return type:str
does_styling

Read-only property: Whether this class instance may emit sequences.

Return type:bool
is_a_tty

Read-only property: Whether stream is a terminal.

Return type:bool
height

Read-only property: Height of the terminal (in number of lines).

Return type:int
width

Read-only property: Width of the terminal (in number of columns).

Return type:int
location(x=None, y=None)[source]

Context manager for temporarily moving the cursor.

Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:

term = Terminal()
with term.location(2, 5):
    for x in xrange(10):
        print('I can do it %i times!' % x)
print('We're back to the 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.

Note

The store- and restore-cursor capabilities used internally provide no stack. This means that location() calls cannot be nested: only one should be entered at a time.

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:tuple
Returns:cursor position as tuple in form of (x, y).

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 capability u6, or again VT100’s definition of \x1b[%i%d;%dR when undefined.

The (row, col) return value matches the parameter order of the move capability, so that the following sequence should cause the cursor to not move at all:

>>> term = Terminal()
>>> term.move(*term.get_location()))

Warning

You might first test that a terminal is capable of informing you of its location, while using a timeout, before later calling. When a timeout is specified, always ensure the return value is conditionally checked for (-1, -1).

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.

hidden_cursor()[source]

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:
  • x (int) – horizontal position.
  • y (int) – vertical position.
Return type:

ParameterizingString

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:
  • x (int) – horizontal position.
  • y (int) – vertical position.
Return type:

ParameterizingString

Returns:

Callable string that moves the cursor to the given coordinates

move_left

Move cursor 1 cells to the left, or callable string for n>1 cells.

move_right

Move cursor 1 or more cells to the right, or callable string for n>1 cells.

move_up

Move cursor 1 or more cells upwards, or callable string for n>1 cells.

move_down

Move cursor 1 or more cells downwards, or callable string for n>1 cells.

color

A callable string that sets the foreground color.

Return type:ParameterizingString

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:
  • red (int) – RGB value of Red.
  • green (int) – RGB value of Green.
  • blue (int) – RGB value of Blue.
Return type:

FormattingString

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.

on_color

A callable capability that sets the background color.

Return type:ParameterizingString
on_color_rgb(red, green, blue)[source]

Provides callable formatting string to set background color to the specified RGB color.

Parameters:
  • red (int) – RGB value of Red.
  • green (int) – RGB value of Green.
  • blue (int) – RGB value of Blue.
Return type:

FormattingString

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.

rgb_downconvert(red, green, blue)[source]

Translate an RGB color to a color code of the terminal’s color depth.

Parameters:
  • red (int) – RGB value of Red (0-255).
  • green (int) – RGB value of Green (0-255).
  • blue (int) – RGB value of Blue (0-255).
Return type:

int

Returns:

Color code of downconverted RGB color

normal

A capability that resets all video attributes.

Return type:str

normal is an alias for sgr0 or exit_attribute_mode. Any styling attributes previously applied, such as foreground or background colors, reverse video, or bold are reset to defaults.

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(), and keypad().

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.

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.

Parameters:
  • text (str) – String to be aligned
  • width (int) – Total width to fill with aligned text. If unspecified, the whole width of the terminal is filled.
  • fillchar (str) – String for padding the right of text
Return type:

str

Returns:

String of text, left-aligned by width.

rjust(text, width=None, fillchar=' ')[source]

Right-align text, which may contain terminal sequences.

Parameters:
  • text (str) – String to be aligned
  • width (int) – Total width to fill with aligned text. If unspecified, the whole width of the terminal is used.
  • fillchar (str) – String for padding the left of text
Return type:

str

Returns:

String of text, right-aligned by width.

center(text, width=None, fillchar=' ')[source]

Center text, which may contain terminal sequences.

Parameters:
  • text (str) – String to be centered
  • width (int) – Total width in which to center text. If unspecified, the whole width of the terminal is used.
  • fillchar (str) – String for padding the left and right of text
Return type:

str

Returns:

String of text, centered by width

length(text)[source]

Return printable length of a string containing sequences.

Parameters:text (str) – String to measure. May contain terminal sequences.
Return type:int
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:str
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:str
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:str
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:str
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 or term.cuf(5)) are replaced by destructive space or erasing.

split_seqs(text, **kwds)[source]

Return text split by individual character elements and sequences.

Parameters:
  • text (str) – String containing sequences
  • kwds – remaining keyword arguments for re.split().
Return type:

list[str]

Returns:

List of sequences and individual characters

>>> term.split_seqs(term.underline(u'xyz'))
['\x1b[4m', 'x', 'y', 'z', '\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 in text are expanded by string.expandtabs().
  • width (int) – Unlike textwrap.wrap(), width will default to the width of the attached terminal.
  • kwargs – See textwrap.TextWrapper
Return type:

list

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 supports inkey(), reading only one byte from the keyboard string at a time. This method should always return without blocking if called after kbhit() 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 using getch() without blocking. The standard implementation simply uses the select.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). When timeout is a positive number, returns after timeout seconds have elapsed (float).
Return type:bool
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 to sys.__stdin__.

raw()[source]

A context manager for tty.setraw().

Although both break() and raw() 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 receive by the inkey() 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 to Terminal attribute KEY_END.

However, upon entering keypad(), \\x1b[OF is transmitted, translating to KEY_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) – To distinguish between the keystroke of KEY_ESCAPE, and sequences beginning with escape, the parameter esc_delay specifies the amount of time after receiving escape (chr(27)) to seek for the completion of an application key before returning a Keystroke instance for KEY_ESCAPE.
Return type:

Keystroke.

Returns:

Keystroke, which may be empty (u'') if timeout is specified and keystroke is not received.

Note

When used without the context manager cbreak(), or raw(), sys.__stdin__ remains line-buffered, and this function will block until the return key is pressed!

class WINSZ[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