5.6.11. terminal_utils - Helper functions for input from/output to a terminal#

This module contains modules useful to deal with output on the terminal:

  • Pager, a class to provide paginated output with less similar to other popular tools like git diff

  • InputEditor, a class to open an editor window when requesting longer inputs from users, similar to git commit

class terminal_utils.ANSIColors(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Simple class to handle color output to the terminal.

This class allows to very easily add color output to the terminal

>>> from terminal_utils import ANSIColors as ac
>>> print(f"{ac.fg('red')}Some text in {ac.color(underline=True)}RED{ac.reset()}")

The basic colors can be specified by name (case insensitive) or by enum value. Custom colors can be supplied using hex notation like #rgb or #rrggbb (Hint: matplotlib.colors.to_hex might be useful here). As an example to use the viridis colormap to color the output on the terminal:

from matplotlib import cm
from matplotlib.colors import to_hex
from terminal_utils import ANSIColors as ac

# sample the viridis colormap at 16 points
for i in range(16):
    # convert i to be in [0..1] and get the hex color
    color = to_hex(cm.viridis(i/15))
    # and print the hex color in the correct color
    print(f"{i}. {ac.fg(color)}{color}{ac.reset()}")

If the output is not to a terminal color output will be disabled and nothing will be added to the output, for example when redirecting the output to a logfile.

classmethod bg(color)[source]#

Shorthand for color(background=color)

classmethod color(foreground=None, background=None, bold=False, underline=False, inverted=False)[source]#

Change terminal colors to the given foreground/background colors and attributes.

This will return a string to be printed to change the color on the terminal. To revert to default print the output of reset()

Parameters:
  • foreground (int or str) – foreground color to use, can be any value accepted by convert_color If None is given the current color will not be changed.

  • background (int or str) – background color to use, can be any value accepted by convert_color. If None is given the current color will not be changed.

  • bold (bool) – Use bold font

  • underline (bool) – Underline the text

  • inverted (bool) – Flip background and foreground color

classmethod convert_color(color)[source]#

Convert a color to the necessary ansi code. The argument can either bei

  • an integer corresponding to the ansi color (see the enum values of this class)

  • the name (case insensitive) of one of the enum values of this class

  • a hex color code of the form #rgb or #rrggbb

Raises:

KeyError – if the argument is a string not matching to one of the known colors

classmethod fg(color)[source]#

Shorthand for color(foreground=color)

classmethod reset()[source]#

Reset colors to default

static supported()[source]#

Check whether the output is a terminal.

If this is False, the methods color, fg, bg and reset will only return an empty string as color output will be disabled

class terminal_utils.InputEditor(editor_command: str = None, initial_content: str = None, commentlines_start_with: str = '#')[source]#

Class to get user input via opening a temporary file in a text editor.

It is an alternative to the python commands input() or sys.stdin.readlines and is similar to the behaviour of git commit for editing commit messages. By using an editor instead of the command line, the user is motivated to give expressive multi-line input, leveraging the full text editing capabilities of his editor. This function cannot be used for example in interactive terminal scripts, whenever detailed user input is required.

Heavily inspired by the code in this blog post: https://chase-seibert.github.io/blog/2012/10/31/python-fork-exec-vim-raw-input.html

Parameters:
  • editor_command – Editor to open for user input. If None, get default editor from environment variables. It should be the name of a shell executable and can contain command line arguments.

  • initial_content – Initial string to insert into the temporary file that is opened for user input. Can be used for default input or to insert comment lines with instructions.

  • commentlines_start_with – Optionally define string with which comment lines start

comment_string#

string which starts comments in the file

editor_command_list#

command line for the editor, split to seperate executable name command line arguments

get_editor_command()[source]#

Get editor shell command string used for user input.

initial_content#

initial content of the editor window

input()[source]#

Get user input via editing a temporary file in an editor. If opening the editor fails, fall back to command line input

class terminal_utils.Pager(prompt=None, quit_if_one_screen=False)[source]#

Context manager providing page-wise output using less, similar to how git handles long output of for example git diff. Paging will only be active if the output is to a terminal and not piped into a file or to a different program.

Warning

To be able to see basf2 log messages like B2INFO() on the paged output you have to set basf2.logging.enable_python_logging = True

Changed in version release-03-00-00: the pager no longer waits until all output is complete but can incrementally show output. It can also show output generated in C++

You can set the environment variable $PAGER to an empty string or to cat to disable paging or to a different program (for example more) which should retrieve the output and display it.

>>> with Pager():
>>>     for i in range(30):
>>>         print("This is an example on how to use the pager.")
Parameters:
  • prompt (str) – a string argument allows overriding the description provided by less. Special characters may need escaping. Will only be shown if paging is used and the pager is actually less.

  • quit_if_one_screen (bool) – indicating whether the Pager should quit automatically if the content fits on one screen. This implies that the content stays visible on pager exit. True is similar to the behavior of git diff, False is similar to git --help