terminal.py — Blessed 1.17.7 documentation

# terminal.py

Module containing `Terminal`, the primary API entry point.

class `Terminal`(kind=None, stream=None, force_styling=False)

  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)

    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.

  property `kind`

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

    Return type

      str

  property `does_styling`

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

    Return type

      bool

  property `is_a_tty`

    Read-only property: Whether `stream` is a terminal.

    Return type

      bool

  property `height`

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

    Return type

      int

  property `width`

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

    Return type

      int

  property `pixel_height`

    Read-only property: Height ofthe terminal (in pixels).

    Return type

      int

  property `pixel_width`

    Read-only property: Width of terminal (in pixels).

    Return type

      int

  `location`(x=None, y=None)

    Context manager for temporarily moving the cursor.

    Parameters

      - x (int) – horizontal position, from left, 0, to right edge of screen, self.width - 1.

      - y (int) – vertical position, from top, 0, to bottom of screen, self.height - 1.

    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) of `move()`. This is for API Compaibility with the blessings library, sorry for the trouble!

  `get_location`(timeout=None)

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

    The `(y, x)` return value matches the parameter order of the `move_xy()` 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)

  `fullscreen`()

    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`()

    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)

    A callable string that moves the cursor to the given `(x, y)` screen coordinates.

    Parameters

      - x (int) – horizontal position, from left, 0, to right edge of screen, self.width - 1.

      - y (int) – vertical position, from top, 0, to bottom of screen, self.height - 1.

    Return type

      ParameterizingString

    Returns

      Callable string that moves the cursor to the given coordinates

  `move_yx`(y, x)

    A callable string that moves the cursor to the given `(y, x)` screen coordinates.

    Parameters

      - y (int) – vertical position, from top, 0, to bottom of screen, self.height - 1.

      - x (int) – horizontal position, from left, 0, to right edge of screen, self.width - 1.

    Return type

      ParameterizingString

    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

      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)

    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`.

  property `on_color`

    A callable capability that sets the background color.

    Return type

      ParameterizingString

  `on_color_rgb`(red, green, blue)

    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`.

  `formatter`(value)

    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` or `NullCallableString`

    Returns

      Callable string that sets color and other text formatting options

    Calling `term.formatter('bold_on_red')` is equivalent to `term.bold_on_red`, but a string that is not a valid text formatter will return a `NullCallableString`. This is intended to allow validation of text formatters without the possibility of inadvertently returning another terminal capability.

  `rgb_downconvert`(red, green, blue)

    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

  property `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.

  `link`(url, text, url_id='')

    Display `text` that when touched or clicked, navigates to `url`.

    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.

    Parameters

      - url (str) – Hyperlink URL.

      - text (str) – Clickable text.

      - url_id (str) – Optional ‘id’.

    Return type

      str

    Returns

      String of `text` as a hyperlink to `url`.

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

  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.

  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=' ')

    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=' ')

    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=' ')

    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)

    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)

    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)

    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)

    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)

    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)

    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)

    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`()

    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)

    Buffer input data to be discovered by next call to `inkey()`.

    Parameters

      text (str) – String to be buffered as keyboard input.

  `kbhit`(timeout=None)

    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`()

    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__`.

    Note

    `tty.setcbreak()` sets `VMIN = 1` and `VTIME = 0`, see http://www.unixwiz.net/techtips/termios-vmin-vtime.html

  `raw`()

    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`()

    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)

    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`

  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` = 'dumb'

  str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

  Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.