console Package

console - Comprehensive utility library for ANSI terminals.
© 2018-2025, Mike Miller - Released under the LGPL, version 3+.

console.color_tables module

Tables for known ANSI color palettes.

In order for “color palette downgrade by proximity” to work well, we need to know what the standard 16 color palette of the platform is. Many are recorded here. Palettes are recorded as integer values so proximity can be calculated.

console.ascii4 module

ascii4 - “Þe Auld” Four-Column ASCII Table FTW!

class console.ascii4.SilentString[source]

Bases: str

console.ascii4.print_ascii_chart(link=False, headers=True, unicode_symbols=False)[source]

ascii4 - “Þe Auld” Four-Column ASCII Table FTW!

This four-column table (of thirty-two rows each) helps illustrate the relationships between characters and control codes better than more common ASCII chart layouts:

  • To find the binary representation of a character, concatenate the two digit group code above its column, with its five digit row code:

    Optional 8th bit → 0 10 01000 ⇒ 01001000

    Group code ↗ ↑ Row code ↑ Full Monty byte, aka “H”

  • To generate a control code, a key is pressed then AND-ed with the control key group code of 00, forcing the sixth and seventh most significant bits (from the right!) to zero. This is why, for example:

    • BEL, the Bell may be activated with ^G (column to right)

    • BS, the Backspace key is represented by ^H

    • ESC, the Escape key is represented by ^[, etc.

  • This is also why one can add 32/20h to the index of a capital to find the corresponding lower case letter.

Parameters:
  • characters. (link Add hyperlinks to special) –

  • headers. (no-headers Skip informative) –

  • control-chars. (unicode_symbols Use symbols instead of names for) –

Note

The listing in this format is relatively tall and it is therefore difficult to see everything at once on terminals under ~thirty-two lines in height. The standard eight-column “ascii” command for Unix-likes is recommended under shorter terminals when a complete view is desired.

console.beep module

Cross-platform beep functions. See BoomBox for audio-file playback and tone-generation for sound effects.

console.beep.beep()

Simple system beep for POSIX terminals, may be disabled.

console.beep.beep_curses()[source]

Curses beep.

console.beep.beep_macos(wait_secs=0.5)[source]

Simple audio-system beep for MacOS.

If the program runs too quickly it will get killed before the sound is played. A small sleep, say .5 seconds afterward may be necessary.

console.beep.beep_posix()[source]

Simple system beep for POSIX terminals, may be disabled.

console.beep.beep_windows()[source]

Simple audio-system beep for Windows.

console.constants module

Constants needed cross-package.

console.constants.BEL = '\x07'

7 007 0x07 ^G Terminal bell - Ding!

console.constants.BS = '\x08'

8 010 0x08 ^H Backspace

console.constants.CR = '\r'

13 015 0x0D ^M Carriage return

console.constants.CSI = '\x1b['

Control Sequence Introducer

console.constants.DEL = '\x7f'

127 177 Delete character

console.constants.ENQ = '\x05'

5 005 ^E Enquiry

console.constants.ESC = '\x1b'

27 033 ^[ Escape character

console.constants.FF = '\x0c'

New page NP)

Type:

12 014 0x0C ^L Formfeed (also

console.constants.FS = '\x1c'

28 034 ^ Field Separator

console.constants.GS = '\x1d'

29 035 ^] Group Separator

console.constants.HT = '\t'

9 011 0x09 ^I Horizontal TAB

console.constants.LF = '\n'

10 012 0x0A ^J Linefeed (newline)

console.constants.OSC = '\x1b]'

Operating System Command

console.constants.RIS = '\x1bc'

Reset to Initial State, aka clear screen (see utils)

console.constants.RS = '\x1e'

30 036 ^^ Record Separator

console.constants.ST = '\x1b\\'

Sequence terminator

class console.constants.TermLevel(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

ANSI_BASIC = 2
ANSI_DIRECT = 4
ANSI_EXTENDED = 3
ANSI_MONOCHROME = 1
DUMB = 0
THE_FULL_MONTY = 9
console.constants.VT = '\x0b'

11 013 0x0B ^K Vertical TAB

console.cli module

Convenience command-line interface script for select utility functions and methods that don’t have common implementations. (Optional arguments may be shortened and are recognized when unique.)

console.cli.main(args, kwargs)[source]

Tear the roof off the sucker…

console.cli.setup()[source]

Parse command line, validate, initialize logging, etc.

console.cli.setuptools_entry_point()[source]

This is the new way to get an .exe on Windows. :-/

console.core module

Complicated gobbyldegook supporting the simple color/style interface located here. Classes below are not meant to be instantiated by client code; see style.py.

console.demos module

Demos showing what the library and terminal combo can do.

console.demos.build_demos(caption, obj, extra_style='')[source]

Iterate over a Palette container and collect the items to add to demos.

console.demos.make_header(i)[source]
console.demos.run()[source]

Run the demos.

console.detection module

This module contains capability detection routines for use under ANSI compatible terminals. Most functions return None when not able to detect requested information.

Todo

get_color is run under redirection… it shouldn’t.

console.detection.is_a_tty(outfile=sys.stdout)[source]

Detect terminal or something else, such as output redirection.

Returns:

is tty or None if not found.

Return type:

Boolean, None

class console.detection.TermStack(infile=sys.stdin, encoding='utf8')[source]

Context Manager to save, temporarily modify, then restore terminal attributes. POSIX only.

Arguments::

stream - The file object to operate on, defaulting to stdin. exit_mode - Mode to exit with: now, drain, or flush default.

Raises:

AttributeError – when stream has no attribute ‘fileno’

Example

A POSIX implementation of get char/key:

import tty

with TermStack() as fd:
    tty.setraw(fd)
    print(sys.stdin.read(1))
console.detection.color_is_disabled(**envars)[source]

Look for clues in environment, e.g.:

Parameters:

envars – Additional environment variables to check for equality, i.e. MYAPP_COLOR_DISABLED='1'

Returns:

None or bool

Return type:

disabled

console.detection.color_is_forced(**envars)[source]

Look for clues in environment, e.g.:

Parameters:

envars – Additional environment variables as keyword arguments to check for equality, i.e. MYAPP_COLOR_FORCED='1'

Returns:

bool

Return type:

forced

console.detection.detect_terminal_level()[source]

Returns whether we think the terminal is dumb or supports basic, extended, or direct color sequences. posix version.

This implementation looks at common environment variables, rather than terminfo.

Returns:

None or TermLevel member color_sep: The extended color sequence separator character,

i.e. “:” or “;”.

Return type:

level

console.detection.detect_terminal_level_terminfo()[source]

Use curses to query the terminfo database for the terminal support level

Returns:

TermLevel member color_sep The extended color sequence separator character,

i.e. “:” or “;”.

Return type:

level

console.detection.detect_unicode_support()[source]

Try to detect unicode (utf8?) support in the terminal.

Checks the LANG environment variable, falls back to an experimental method utilizing cursor position. Implementation idea is from the link below:

Returns:

Boolean | None if not a TTY

Return type:

support

console.detection.get_answerback(max_bytes=32, end=('\x07', '\x1b\\', '\n'), timeout=0.2)[source]

Returns the “answerback” string which is often empty, None if not available.

Warning: Hangs unless max_bytes is a subset of the answer string or an

explicit end character(s) given, due to inability to find end. https://unix.stackexchange.com/a/312991/159110

console.detection.get_color(name, number=None, timeout=0.2)[source]

Query the default terminal, for colors, etc.

Direct queries supported on xterm, iTerm, perhaps others.

Parameters:
  • name – str, one of (‘foreground’, ‘fg’, ‘background’, ‘bg’, or ‘index’) # index grabs a palette index

  • number – int, if name is index, should be an ANSI color index from 0…255,” see links below.

Queries terminal using OSC # ? BEL sequence, call responds with a color in this X Window format syntax:

Returns:

A tuple of four-digit hex strings after parsing, the last two digits are the least significant and can be chopped when needed:

('DEAD', 'BEEF', 'CAFE')

If an error occurs during retrieval or parsing, the tuple will be empty.

Return type:

tuple[str]

Examples

>>> get_color('bg')
... ('0000', '0000', '0000')
>>> get_color('index', 2)       # second color in indexed
... ('4e4d', '9a9a', '0605')    # palette, 2 aka 32 in basic

Notes

Query blocks until timeout if terminal does not support the function. Many don’t. Timeout can be disabled with None or set to a higher number for a slow terminal.

On Windows, only able to find palette defaults, which may be different if they were customized.

console.detection.get_position(fallback=(0, 0))[source]

Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline.

Returns:

(x, y) | (0, 0) - fallback, if an error occurred.

Return type:

tuple(int)

console.detection.get_size(fallback=(80, 24))[source]

Convenience copy of shutil.get_terminal_size for use here.

>>> get_terminal_size(fallback=(80, 24))
os.terminal_size(columns=120, lines=24)
console.detection.get_theme(timeout=0.2, default=None)[source]

Checks terminal for light/dark theme information.

First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows (not WSL) and xterm, perhaps others. See notes on get_color().

Parameters:
  • timeout – int, time before giving up

  • default – string, fallback value

Returns:

‘dark’, ‘light’, or None if no information.

Return type:

str, None

console.detection.get_title(mode='title')[source]

Return the terminal/console title.

Parameters:

str – mode, one of (‘title’, ‘icon’) or int (20-21): see links below.

Returns:

title string, or None if not able to be found.

Note

Few terms besides xterm support this for security reasons. iTerm returns “”. MATE Terminal returns “Terminal”.

console.detection.init(using_terminfo=False, _stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, _basic_palette=())[source]

Automatically determine whether to enable ANSI sequences, and if so, what level of functionality is available. Takes a number of factors into account, e.g.:

  • Whether output stream is a TTY.

  • User preference environment variables:

    • CLICOLOR, CLICOLOR_FORCE, NO_COLOR``

  • Detection results:

    • The terminfo database, if requested or run remotely via SSH.

    • Or a further inspection of the environment:

      • TERM, ANSICON, COLORTERM configuration variables

      • Are standard output streams wrapped by colorama on Windows?

Parameters:
  • using_terminfo – 2B || !2B # that is the question…

  • _stream – Which output file to check: stdout, stderr

  • _basic_palette – Force the platform-dependent 16 color palette, for testing. Tuple of 16 rgb-int tuples.

Returns:

None or TermLevel member

Return type:

level

Note

This is the main function of the module—meant to be used unless requirements are more specific.

console.detection.parse_vtrgb(path='/etc/vtrgb')[source]

Parse the color table for the Linux console.

Returns:

palette or None if not found.

console.disabled module

Singletons that mimic the style/palette/entry interface but do not print ANSI control sequences, i.e.: for use when a terminal doesn’t support them.

console.disabled.empty = ''

A passive, empty, and “falsey” string.

https://youtu.be/sFacWGBJ_cs

console.viewers module

An EXPERIMENTAL module containing an HTML to ANSI sequence converter. It supports quick rich-text in scripting applications for those familiar with HTML. Why invent another styling language?

Currently is partially useful. No CSS class support yet, but many inline styles that correspond to terminal capabilities work.

class console.viewers.HeaderMode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

DOUBLE = 3
FIGLET = 2
NORMAL = 1
class console.viewers.LiteHTMLParser(*, convert_charrefs=True)[source]

Bases: HTMLParser

Parses simple HTML tags, returns as text and ANSI sequences.

Exmaple:

parser = LiteHTMLParser()
parser.feed(text)
result = ''.join(parser.tokens)  # build and return final string
parser.tokens.clear()
handle_data(data)[source]

Deals with text between and outside the tags. Cases:

' '
' word

word’

‘word’, ‘word ‘, ‘ word’

handle_endtag(tag)[source]
handle_starttag(tag, attrs)[source]
tokens = []
class console.viewers.StringCache(palette, **kwargs)[source]

Bases: dict

Used to cache rendered ANSI color/fx strings with a dictionary lookup interface.

console.viewers.hprint(*args, newline=False, **kwargs)[source]

Print function for terminals, with limited HTML support.

console.viewers.hrender(text)[source]

Renders HTML to an ANSI-compatible string.

console.viewers.view(path)[source]

Display text files, converting formatting to equivalent ANSI escapes. Currently supports limited-HTML only.

console.progress module

Experimental Progress Bar functionality.

A demo is available via command-line:

▶ python3 -m console.progress [-l] [-d]  # label and debug modes

Todo

  • Gradients/rainbar

  • Additional tests

class console.progress.HiDefProgressBar(**kwargs)[source]

Bases: ProgressBar

A ProgressBar with increased, sub-character cell resolution, approx 8x.

Most useful in constrained environments (a small terminal window) and/or long-running tasks.

Parameters:
  • width – 8 or greater

  • progress (partial_chars - sequence of characters to show) –

icons = ('▕', '▉', '▉', '▏', '✓', '⏴', '⏵', '✗ ')
min_width = 8
partial_char_extra_style = '\x1b[48;5;236m'
partial_chars = ('░', '▏', '▎', '▍', '▌', '▋', '▊', '▉')
partial_chars_len = 8
class console.progress.ProgressBar(iterable=None, **kwargs)[source]

Bases: object

A stylable bar graph for displaying the current progress of task completion.

The execution flows like this:

  • __init__()

  • bar() # __call__() by code to set parameters
    • _update_status() # check errors and set progress label

  • __str__() # and when printed
    • render()

Example:

from time import sleep  # demo purposes only
from console.screen import sc
from console.progress import ProgressBar

with sc.hidden_cursor():

    items = range(256)      # example tasks
    bar = ProgressBar(total=len(items))  # set total

    # simple loop
    for i in items:
        print(bar(i), end='', flush=True)
        sleep(.02)
    print()

    # with caption
    for i in items:
        print(bar(i), f' copying: /path/to/img_{i:>04}.jpg',
              end='', flush=True)
        sleep(.1)
    print()

    # or use as a simple tqdm-style iterable wrapper:
    for i in ProgressBar(range(100)):
        sleep(.1)
Parameters:
  • clear_left – True True to clear and mv to 0, or int offset.

  • debug – None Enable debug output.

  • done – False True on completion, moderates style

  • expand – False Set width to full terminal width

  • iterable – object An object to iterate on, see tqdm example.

  • label_mode – True Enable progress percentage label

  • oob_error – False Out of bounds error occurred.

  • total – 100 Set the total number of items.

  • unicode_support – bool Detection result, determines default icons

  • width – 32 Full width of bar, padding, and labels.

  • icons – (,,,) Tuple of chars

  • styles – (,,,) Tuple of ANSI styles

  • theme – ‘name’ String name of combined icon & style set

  • label_fmt – (‘%3.0f%%’, ‘%4.1f%%’, ‘%5.2f%%’) Precision—defaults to no decimal places. After each timedelta, label precision is increased.

  • timedeltas – (60, 300) | None Thresholds in seconds, to increase label precision

property clear_left
debug = None
done = False
expand = False
icons = (' ', '▮', '▯', ' ', '✓', '⏴', '⏵', '✗')
label_fmt = ('%3.0f%%', '%4.1f%%', '%5.2f%%')
label_fmt_str = '%4s'
label_mode = True
oob_error = False
reset()[source]

Reset the bar, start time only for now.

styles = ('\x1b[2;38;5;70m', '\x1b[38;5;70m', '\x1b[38;5;24m', '\x1b[2;38;5;24m', '\x1b[2;38;5;70m', '\x1b[91m')
theme = 'default'
timedeltas = (60, 300)
total = None
unicode_support = True
width = 32
console.progress.install_resize_handler()[source]

Signal handling code - handles the situation when full-width bars are created via expand = True, and the virtual terminal width changes.

Note: Unix only

console.progress.progress(value: float, clear_left=True, expand=False, label_mode=True, list_themes=False, theme='default', total: int = 100, width=32, debug=False)[source]

Convenience function for building a one-off progress bar, for scripts and CLI, etc.

Parameters:
  • value. (value The current) –

  • clear_left – True True to clear and mv to 0, or int offset

  • debug – None Enable debug output

  • expand – False Set width to full terminal width

  • label_mode – True Enable progress percentage label

  • total – 100 Set the total number of items

  • width – 32 Full width of bar, padding, and labels

Note

If you’d like value to signify a percentage instead, pass --total 100 or other round number as well.

Run python3 -m console.progress -l for a demo.

console.proximity module

Given an (3x) 8-bit RGB color, find the closest extended 8-bit terminal color index.

Nearest-color algorithm derived from:

pygments.formatters.terminal256
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Formatter for 256-color terminal output with ANSI sequences.

RGB-to-XTERM color conversion routines adapted from xterm256-conv
tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
by Wolfgang Frisch.

:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.

Note

An experiment was done using a more accurate CIELAB distance algorithm, but the solution was quite heavy and therefore removed.

console.proximity.build_color_tables(base=((0, 0, 0), (170, 0, 0), (0, 170, 0), (170, 85, 0), (0, 0, 170), (170, 0, 170), (0, 170, 170), (170, 170, 170), (85, 85, 85), (255, 85, 85), (85, 255, 85), (255, 255, 85), (85, 85, 255), (255, 85, 255), (85, 255, 255), (255, 255, 255)))[source]

Create the color tables for palette downgrade support, starting with the platform-specific 16 from the color tables module. Save as global state. :-/

console.proximity.find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid')[source]

Given a three or six-character hex digit string, return the nearest color index.

Parameters:

hexdigits – a three/6 digit hex string, e.g. ‘b0b’, ‘123456’

Returns:

index, or None on error.

Return type:

int, None

console.proximity.find_nearest_color_index(r, g, b, color_table=None, method='euclid')[source]

Given three integers representing R, G, and B, return the nearest color index.

Parameters:
  • r – int - of range 0…255

  • g – int - of range 0…255

  • b – int - of range 0…255

Returns:

index, or None on error.

Return type:

int, None

console.screen module

This module generates ANSI character codes to manage terminal screens and move the cursor around, via a Screen class.

For the cursor and view “move to” instruction, Screen classes default to standard (x, y) coordinate order and also use 0-based locations as does Python curses. This means the coordinates of the the cup and hvp instructions will also have 1 added to each value on output.

If you’d prefer a (y, x) coordinate order as in the ANSI/Curses sequences, pass the parameter swap=False on initialization.

Context-managers with contextlib inspired by:

blessings.__init__.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A thin, practical wrapper around terminal coloring, styling, and
positioning.

:copyright: Copyright 2011-2018, Erik Rose
:license: MIT License (MIT)
class console.screen.Screen(force=None, **kwargs)[source]

Bases: _ContextMixin

Convenience class for cursor and screen manipulation.

Short names (terminfo capnames) are defined below, while the NAME_TO_TERMINFO_MAP mapping defines easier to remember verbose names.

ScreenTermInfo defaults to standard (x, y) coordinate order and uses 0-based locations as does Python curses.

Example:

from console.screen import sc

>>> sc.move_to
'[%s;%sH'

>>> sc.move_to(3, 6)
''  # swapped and incremented to ANSI format.

https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

cbt = 'Z'
cht = 'I'
civis = '\x1b[?25l'
cnl = 'E'
cnorm = '\x1b[?25h'
cpl = 'F'
cub = 'D'
cud = 'B'
cuf = 'C'
cup = ('H', '%s;%s')
cuu = 'A'
dch = 'P'
dl = 'M'
ech = 'X'
ed = 'J'
el = 'K'
static get_position(fallback=(0, 0))

Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline.

Returns:

(x, y) | (0, 0) - fallback, if an error occurred.

Return type:

tuple(int)

hpa = 'G'
hvp = ('f', '%s;%s')
ich = '@'
il = 'L'
rc = '\x1b8'
rmcup = '\x1b[?1049l'
rs1 = '\x1bc'
sc = '\x1b7'
sd = 'T'
smcup = '\x1b[?1049h'
su = 'S'
vpa = 'd'
class console.screen.ScreenTermInfo(force=False, **kwargs)[source]

Bases: _ContextMixin

Convenience class for cursor and screen manipulation.

Short names (terminfo capnames) are available, while the NAME_TO_TERMINFO_MAP mapping defines several easier to remember verbose names.

This implementation uses Terminfo instead of hard-coded ANSI sequences.

ScreenTermInfo defaults to standard (x, y) coordinate order and uses 0-based locations as does Python curses. Use swap=False to reverse that.

Example:

>>> sc.move_to
'[%i%p1%d;%p2%dH'

>>> sc.move_to(3, 6)
''  # swap and incremented to ANSI format.

https://en.wikipedia.org/wiki/Terminfo

static get_position(fallback=(0, 0))

Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline.

Returns:

(x, y) | (0, 0) - fallback, if an error occurred.

Return type:

tuple(int)

console.style module

This module is focused on the escape codes concerning character styles and colors interpreted by terminals, sometimes called “SGR (Select Graphic Rendition) parameters.”

A number of classes below facilitate using them. See:

class console.style.BackgroundPalette(color_sep=None, level=Ellipsis)[source]

Bases: _HighColorPaletteBuilder

Container for background color codes.

Parameters:
  • support. (autodetect - Attempt to detect palette) –

  • disabled (palettes - If autodetect) – explicitly. str, seq, or None

  • support (set palette) – explicitly. str, seq, or None

See:

https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit

black = 40
blue = 44
cyan = 46
default = 49
green = 42
lightblack = 100
lightblue = 104
lightcyan = 106
lightgreen = 102
lightmagenta = 105
lightpurple = 105
lightred = 101
lightwhite = 107
lightyellow = 103
magenta = 45
purple = 45
red = 41
white = 47
yellow = 43
class console.style.EffectsPalette(color_sep=None, level=Ellipsis)[source]

Bases: _MonochromePaletteBuilder

Container for text style codes.

Bold, italic, underline, blink, reverse, strike, fonts, etc.

Parameters:
  • support. (autodetect - Attempt to detect palette) –

  • disabled (palettes - If autodetect) – explicitly. str, seq, or None

  • support (set palette) – explicitly. str, seq, or None

See:

https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters

b = (1, 22)
bold = (1, 22)
conceal = (8, 28)
crossed = (9, 29)
curly_underline = ('4:3', 24)
default = (0, 0)
dim = (2, 22)
double_underline = (21, 24)
dunder = (21, 24)
encircle = (52, 54)
end = (0, 0)
frame = (51, 54)
hide = (8, 28)
i = (3, 23)
italic = (3, 23)
overline = (53, 55)
reverse = (7, 27)
s = (9, 29)
strike = (9, 29)
u = (4, 24)
underline = (4, 24)
class console.style.EffectsTerminator(color_sep=None, level=Ellipsis)[source]

Bases: _MonochromePaletteBuilder

“I’ll be baaahhhck.”

Rarely used codes to turn off specific style features, not supported at times. Generally, use of EffectsPalette.end is simpler and more reliable.

Parameters:
  • support. (autodetect - Attempt to detect palette) –

  • disabled (palettes - If autodetect) – explicitly. str, seq, or None

  • support (set palette) – explicitly. str, seq, or None

See:

https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters

b = 22
bg = 49
bold = 22
conceal = 28
crossed = 29
default = 0
dim = 22
encircle = 54
end = 0
fg = 39
font = 10
frame = 54
hide = 28
i = 23
ideogram = 65
italic = 23
overline = 55
reverse = 27
s = 29
strike = 29
u = 24
ul_color = 59
underline = 24
class console.style.ForegroundPalette(color_sep=None, level=Ellipsis)[source]

Bases: _HighColorPaletteBuilder

Container for foreground color codes.

Parameters:
  • support. (autodetect - Attempt to detect palette) –

  • disabled (palettes - If autodetect) – explicitly. str, seq, or None

  • support (set palette) – explicitly. str, seq, or None

See:

https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit

black = 30
blue = 34
cyan = 36
default = 39
green = 32
lightblack = 90
lightblue = 94
lightcyan = 96
lightgreen = 92
lightmagenta = 95
lightpurple = 95
lightred = 91
lightwhite = 97
lightyellow = 93
magenta = 35
purple = 35
red = 31
white = 37
yellow = 33
class console.style.UnderlinePalette(color_sep=None, level=Ellipsis)[source]

Bases: _HighColorPaletteBuilder

Container for color codes specific to underlines. ddSupported by libvte and kitty.

This palette supports extended and true color sequences only. However the first 16 colors of extended coincide with standard colors, so are available there, e.g.: ul.i_0 to ul.i_15

Parameters:
  • support. (autodetect - Attempt to detect palette) –

  • disabled (palettes - If autodetect) – explicitly. str, seq, or None

  • support (set palette) – explicitly. str, seq, or None

Notes

https://sw.kovidgoyal.net/kitty/protocol-extensions.html

#colored-and-styled-underlines

https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit

default = 59

console.test_suite module

Testen-Sie, bitte. Supported under Linux with a libvte terminal.

console.utils module

This module contains cross-platform utility and convenience functions for use under ANSI-compatible terminals. It is focused on Operating System Command (OSC) functionality and includes a few screen-based convenience functions.

See also

console.utils.clear(mode=2)

Clear the terminal/console screen. (Also aliased to clear.)

Parameters:

mode

int | str

0 | ‘forward’ - Clear cursor to end of screen, cursor stays.
1 | ‘backward’ - Clear cursor to beginning of screen, “”
2 | ‘full’ - Clear entire visible screen, cursor to 1,1.
3 | ‘history’ - Clear entire visible screen and scrollback buffer (xterm).

Returns: text sequence to be written, for testing.

console.utils.clear_line(mode=2)[source]

Clear the current line.

Parameters:

mode

int | str

0 | ‘forward’ | ‘right’ - Clear cursor to end of line.
1 | ‘backward’ | ‘left’ - Clear cursor to beginning of line.
2 | ‘full’ - Clear entire line.

Returns: text sequence to be written, for testing.

Note

Cursor position does not change.

console.utils.clear_lines(lines: int, mode=2)[source]

Clear the given number of lines above.

Parameters:
  • lines

    • number of lines above to clear.

  • mode

    int | str

    0 | ‘forward’ | ‘right’ - Clear cursor to end of line.
    1 | ‘backward’ | ‘left’ - Clear cursor to beginning of line.
    2 | ‘full’ - Clear entire line.

Returns: text sequence to be written, for testing.

console.utils.clear_screen(mode=2)[source]

Clear the terminal/console screen. (Also aliased to clear.)

Parameters:

mode

int | str

0 | ‘forward’ - Clear cursor to end of screen, cursor stays.
1 | ‘backward’ - Clear cursor to beginning of screen, “”
2 | ‘full’ - Clear entire visible screen, cursor to 1,1.
3 | ‘history’ - Clear entire visible screen and scrollback buffer (xterm).

Returns: text sequence to be written, for testing.

console.utils.cls()

Reset the terminal/console screen. (Also aliased to cls.)

Greater than a fullscreen terminal clear, also clears the scrollback buffer. May expose bugs in dumb terminals.

console.utils.flash(seconds=0.1)[source]

Flash screen, i.e. turn on reverse video and back again, given a delay in floating-point seconds. Useful as a visible bell.

Parameters:

seconds – float - how long to wait in reverse video

Returns: text sequence to be written, for testing.

console.utils.get_clipboard(source='c', encoding='utf8', max_bytes=65536, timeout=0.2)[source]

Read string or byte data from the clipboard.

Parameters:
  • source – (int | str) of {c, p, q, s, 0-7} (clipboard, primary, secondary, selection, buffers 0-7)

  • encoding – str - decode to unicode or pass None for bytes.

  • max_bytes – int - minor impediment to sending too much text.

  • timeout – float - seconds give up if answer not received in time.

Returns: data found

Note

Works on xterm, hterm, not many other terminals. https://invisible-island.net/xterm/ctlseqs/ctlseqs.html #h3-Operating-System-Commands

console.utils.len_stripped(text)[source]

Convenience - returns the length of a string minus escape sequences.

Useful to find if a string will fit inside a given length on screen.

Returns a terminal hyperlink, given a link and caption text.

Parameters:
  • target – str. Link to the destination, ‘http://foo.bar/baz

  • caption – str | None Optional descriptive text, defaults to target, e.g. ‘Clicken Sie hier!’

  • icon – str Add link icon to end of text, e.g. icon=’🔗’

  • params – str: str Optional key word args, to be formatted as: ‘id=xyz123:foo=bar:baz=quux’ (See note below.)

  • _max_url_len – spec recommendations, see meta.py

  • _max_val_len – spec recommendations, see meta.py

Returns: text sequence to be written, caption, or empty string.

Example:

from console import fg, fx
from console.utils import make_hyperlink

link = make_hyperlink('ftp://ftp.netscape.com/…/navigator.tar.gz',
                      'Blast from the past!')
link_style = fg.blue + fx.underline
print(link_style(link))  # full effect https://youtu.be/BPcr1EDohiQ

Note

This function doesn’t print the escape sequence so it may be styled more easily. Experimental, see below for details:

console.utils.make_line(string='─', width=0, color=None, center=False, _fallback=80)[source]

Build a header-rule style line, using Unicode characters.

Parameters:
  • repeat. (string A character or short string to) –

  • line (color A color name to assign to the) –

  • dim. (defaults to) –

  • characters (width How long the line should be in) – defaults (zero) to full width of terminal.

:param : defaults (zero) to full width of terminal. :param center If a specific width is given: :param center it between spaces.:

New lines are handled by the caller. If the default width of the terminal is used, or center is given, no newline is necessary.

console.utils.make_sized(text, double=True, wide=False)[source]

Returns a sequence to print wide and/or double-sized text. Pertains to the whole line, doesn’t reset to normal until a newline occurs.

Parameters:
  • size. (text The text to change) –

  • font. (wide Use the double-wide) –

  • font.

Note

  • DEC sequences supported on xterm and Konsole, possibly others.

  • Double text is also wide so both options together are redundant. Wide therefore takes precedence.

console.utils.measure(start=1, limit=200, offset=0, newlines=True)[source]

Returns a ruler-style line of measurement across the width of the terminal. Each column number should be read top down:

# ↓  Column 124
..1.
..2.
..4.
Parameters:
  • with (start The number to start) –

  • 1 (e.g. 0 or) –

  • at. (limit The column to limit to or end) –

  • right. (offset Number of spaces to push to the) –

  • line. (newlines Whether to insert newlines after each) – Not strictly needed but helps when the window is cromulently embiggened.

Note

This function for debugging, few apps will need it.

console.utils.notify_cwd(path=None)[source]

Notify the terminal of the current working directory. EXPERIMENTAL

Parameters:

path – str, do not url encode.

Returns: text sequence to be written, for testing.

Notes

https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/20 https://conemu.github.io/en/AnsiEscapeCodes.html#OSC_Operating_system_commands

console.utils.notify_message(message, title='')[source]

Notify the user with the given message. EXPERIMENTAL

Parameters:
  • message – str

  • title – str rxvt-unicode only.

Returns: text sequence to be written, for testing.

Notes

iterm2, rxvt with plugin, kitty https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/13

console.utils.notify_progress(*args, **kwargs)[source]

Function not implemented.

console.utils.pause(message='Press any key to continue…', _return_key=False)[source]

Analogous to the DOS pause command from olden times, with a modifiable message. “Where’s the any key?”

Parameters:

message – str

Returns:

One character or ESC - depending on key hit. None - immediately under i/o redirection, not an interactive tty.

Return type:

str, None

console.utils.reset_terminal()[source]

Reset the terminal/console screen. (Also aliased to cls.)

Greater than a fullscreen terminal clear, also clears the scrollback buffer. May expose bugs in dumb terminals.

console.utils.set_clipboard(data, destination='c', encoding='utf8', max_bytes=65536)[source]

Write string or byte data to the clipboard.

Parameters:
  • data – str | bytes

  • destination – (int | str) of {c, p, q, s, 0-7} (clipboard, primary, secondary, selection, buffers 0-7)

  • encoding – str - if string is passed, encode to bytes

  • max_bytes – int minor impediment to sending too much text.

Returns: text sequence to be written or None, for testing.

Note

Works on xterm, not many other terminals. https://invisible-island.net/xterm/ctlseqs/ctlseqs.html #h3-Operating-System-Commands

console.utils.set_title(title, mode=0)[source]

Set the title of the terminal window/tab/icon.

Parameters:
  • title – str

  • mode

    0 | ‘both’ - Set icon/taskbar and window/tab title
    1 | ‘icon’ - Set only icon/taskbar title
    2 | ‘title’ - Set only window/tab title

Returns: text sequence to be written or None, for testing.

console.utils.strip_ansi(text, c1=False, osc=False)[source]

Strip ANSI escape sequences from a portion of text. https://stackoverflow.com/a/38662876/450917

Parameters:
  • line – str

  • c1 – bool - include C1 based commands in the strippage.

  • osc – bool - include OSC commands in the strippage.

Returns: stripped text

Notes

Enabling both C1 and OSC stripping is less efficient and the two options can mildly conflict with one another. The less problematic order was chosen, but there may still be rare C1/OSC fragments left over.

console.utils.wait_key(keys=None)[source]

Waits for a keypress at the console and returns it.

Parameters:
  • passed (keys - if) – may be a tuple.

  • key (wait for this specific) – may be a tuple.

  • 'Q' (e.g.) – may be a tuple.

  • 'ESC'. – may be a tuple.

Returns:

char or ESC - depending on key hit. None - immediately under i/o redirection, not an interactive tty.

console.windows module

Module for traditional Windows API crud (though not WSL). Typically, it is not necessary to use this module directly; the detection/utils modules are preferred.

https://docs.microsoft.com/en-us/windows/console/console-reference

class console.windows.CONSOLE_SCREEN_BUFFER_INFO[source]

Bases: object

Struct from wincon.h.

console.windows.add_os_sysexits()[source]

Make the sysexit.h exit-status constants available under Windows.

console.windows.cls()[source]

Clear (reset) the console.

console.windows.detect_terminal_level(basic_palette=None)[source]

Returns whether we think the terminal supports basic, extended, or direct color; None if not able to tell. Windows variant.

Returns:

None or TermLevel member color_sep The extended color sequence separator character,

i.e. “:” or “;”.

Return type:

level

console.windows.detect_unicode_support(codepage='cp65001')[source]

Return whether unicode/utf8 is supported by the console/terminal.

console.windows.enable_vt_processing()[source]

What it says on the tin.

Returns:

Tuple of status codes from SetConsoleMode for (stdout, stderr).

console.windows.get_code_page()[source]

Return the code page for this console/terminal instance.

console.windows.get_color(name, number=None, timeout=None)[source]

Query the default terminal for colors, etc.

Parameters:
  • name – str - one of (‘foreground’, ‘fg’, ‘background’, ‘bg’)

  • number – compatibility only

  • timeout – compatibility only

Returns:

A tuple of four-digit hex strings after parsing, the last two digits are the least significant and can be chopped when needed:

('DEAD', 'BEEF', 'CAFE')

If an error occurs during retrieval or parsing, the tuple will be empty.

Return type:

tuple[str]

Examples

>>> get_color('bg')
... ('0000', '0000', '0000')
>>> get_color('index', 2)       # second color in indexed
... ('4e4d', '9a9a', '0605')    # palette, 2 aka 32 in basic

Notes

On Windows, only able to find palette defaults, which may be different if they were customized.

console.windows.get_color_id(name, stream=-11)[source]

Returns current color ids of console.

https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo

Parameters:
  • name – one of (‘background’, ‘bg’, ‘foreground’, ‘fg’)

  • stream – Handle to stdout, stderr, etc.

Returns:

a color id offset from the conhost palette.

Ids 8 and under are dark colors, above light. Id numbers are converted to ANSI order.

Return type:

int

console.windows.get_position(stream=-11)[source]

Returns current position of cursor, starts at 1.

console.windows.get_theme(timeout=0.2)[source]

Checks terminal for light/dark theme information.

First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color().

Returns:

‘dark’, ‘light’, None if no information.

Return type:

str, None

console.windows.get_title(mode=None)[source]

Returns console title string.

https://docs.microsoft.com/en-us/windows/console/getconsoletitle

console.windows.is_ansi_capable()[source]

Check to see whether this version of Windows is recent enough to support “ANSI VT”” processing.

console.windows.is_colorama_installed(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Detect if the colorama stream wrapper has been initialized.

console.windows.set_position(x, y, stream=-11)[source]

Sets current position of the cursor.

console.windows.set_title(title)[source]

Set the console title.