console Package

console - Comprehensive utility library for ANSI terminals.
© 2018, 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

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 0x7F 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)[source]

Bases: enum.IntEnum

An enumeration.

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.beep module

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

console.beep.beep(**kwargs)

Simple system beep for POSIX terminals, may be disabled.

console.beep.beep_macos(**kwargs)[source]

Simple system beep for MacOS.

console.beep.beep_posix(**kwargs)[source]

Simple system beep for POSIX terminals, may be disabled.

console.beep.beep_windows(**kwargs)[source]

Simple 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 0x7F 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)[source]

Bases: enum.IntEnum

An enumeration.

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.core module

Complicated gobbyldegook supporting simple user interfaces located here.

Classes below not meant to be instantiated by client code.

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.

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.

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

Disabled

Return type

None, Bool

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

Forced

Return type

Bool

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

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

Return type

level

console.detection.detect_unicode_support()[source]

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

Checks the LANG environment variable or Windows code page, falls back to an experimental method. Implementation idea is from the link below:

Returns

Boolean | None if not a TTY

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) | (,) - empty, 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)[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.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(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, basic_palette=None)[source]

Automatically determine whether to enable ANSI sequences, and if so, what level of functionality is available.

Takes the following factors into account:

  • User preference environment variables:

    • CLICOLOR, CLICOLOR_FORCE, NO_COLOR``

  • Whether output stream is a TTY.

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

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.disabled.empty_bin

Collection that returns EmptyAttributes on any attribute access.

console.printers module

This module contains an HTML to ANSI sequence printer. It supports quick rich text in scripting applications for those familiar with HTML. Why invent another styling language?

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

TODO: maybe lists

class console.printers.LiteHTMLParser(*, convert_charrefs=True)[source]

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

class console.printers.LiteHTMLParser(*, convert_charrefs=True)[source]

Bases: html.parser.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.printers.StringCache(palette, **kwargs)[source]

Bases: dict

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

console.printers.hprint(*args, **kwargs)[source]

Print function for terminals, with limited HTML support.

console.printers.print(*args, **kwargs)

Print function for terminals, with limited HTML support.

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: console.progress.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

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

icons = ('▕', '▉', '▉', '▏', '✓', '⏴', '⏵', '✗ ')
min_width = 8
partial_char_extra_style = ''
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.

ProgressBar is 0-based, i.e. think 0-99 rather than 1-100 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.

  • 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 = ('', '', '', '', '', '')
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.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.

Note: The attributes of the Screen container currently are not directly composable with the core._PaletteEntry due to the fact that many of them need parameters. This may change in the future.

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)
Note: these could probably be loaded from curses/terminfo,

but haven’t yet found a need.

TODO: These objects don’t compose like the core objects.

class console.screen.Screen(force=False)[source]

Bases: object

Convenience class for cursor and screen manipulation.

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

alt_screen_disable = '\x1b[?1049l'
alt_screen_enable = '\x1b[?1049h'
asoff = '\x1b[?1049l'
ason = '\x1b[?1049h'
auxoff = '\x1b[4i'
auxon = '\x1b[5i'
backward = 'D'
bpoff = '\x1b[?2004l'
bpon = '\x1b[?2004h'
bracketed_paste()[source]

Context Manager that brackets-the-paste:

with screen.bracketed_paste():
    print('Hit me with your best shot…')
bracketedpaste_disable = '\x1b[?2004l'
bracketedpaste_enable = '\x1b[?2004h'
cha = 'G'
cnl = 'E'
cpl = 'F'
cub = 'D'
cud = 'B'
cuf = 'C'
cup = ('H', '%s;%s')
cuu = 'A'
cva = 'd'
down = 'B'
dsr = '\x1b[6n'
ed = 'J'
el = 'K'
erase = 'J'
erase_line = 'K'
forward = 'C'
fullscreen()[source]

Context Manager that enters full-screen mode and restores normal mode on exit.

with screen.fullscreen():
    print('Hello, world!')
hidden_cursor()[source]

Context Manager that hides the cursor and restores it on exit.

with screen.hidden_cursor():
    print('Clandestine activity…')
hide_cursor = '\x1b[?25l'
hpa = 'G'
hvp = ('f', '%s;%s')
left = 'D'
loc = '\x1b[6n'
location(x=None, y=None)[source]

Temporarily move the cursor, perform work, and return to the previous location.

with screen.location(40, 20):
    print('Hello, world!')
mv = ('H', '%s;%s')
mv2 = ('f', '%s;%s')
mv_x = 'G'
mv_y = 'd'
next_line = 'E'
normal_video = '\x1b[?5l'
prev_line = 'F'
rare_mode()[source]

Context Manager that temporarily turns off echo and line-editing functionality; still recognizes Ctrl-C break, Ctrl-Z suspend, etc. Also known as “cbreak” mode.

POSIX only. See getpass for a simple function.

with screen.rare_mode():
    read_keys()
raw_mode()[source]

Context Manager that temporarily that temporarily sets terminal to raw mode.

POSIX only. See utils.wait_key() if looking for a simple read-key function.

with screen.raw_mode():
    read_raw_keypresses()
rcp = '\x1b[u'
reset = '\x1bc'
rest_pos = '\x1b8'
rest_pos2 = '\x1b[u'
restore_title = ('t', '23;%s')
reverse_video = '\x1b[?5h'
right = 'C'
save_pos = '\x1b7'
save_pos2 = '\x1b[s'
save_title = ('t', '22;%s')
scp = '\x1b[s'
scroll_down = 'T'
scroll_up = 'S'
sd = 'T'
show_cursor = '\x1b[?25h'
su = 'S'
up = 'A'
vpa = 'd'

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(level=Ellipsis)[source]

Bases: console.core._HighColorPaletteBuilder

Container for background color codes.

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

  • - If autodetect disabled, set palette support (palettes) – 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(level=Ellipsis)[source]

Bases: console.core._BasicPaletteBuilder

Container for text style codes.

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

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

  • - If autodetect disabled, set palette support (palettes) – 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(level=Ellipsis)[source]

Bases: console.core._BasicPaletteBuilder

“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
  • - Attempt to detect palette support. (autodetect) –

  • - If autodetect disabled, set palette support (palettes) – 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
underline = 24
class console.style.ForegroundPalette(level=Ellipsis)[source]

Bases: console.core._HighColorPaletteBuilder

Container for foreground color codes.

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

  • - If autodetect disabled, set palette support (palettes) – 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(level=Ellipsis)[source]

Bases: console.core._HighColorPaletteBuilder

Container for color codes specific to underlines. EXPERIMENTAL, see notes. Supported 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
  • - Attempt to detect palette support. (autodetect) –

  • - If autodetect disabled, set palette support (palettes) – 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.

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, mode=2)[source]

Clear the given number of lines above.

Parameters
  • lines – int - 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. This can be 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
  • data – str

  • 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

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

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

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))  # in full effect

Note

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

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

Notify the terminal of the current working directory.

Parameters

path – str

Returns: text sequence to be written, for testing.

Notes

https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/20 https://gitlab.com/gnachman/iterm2/-/issues/3939

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

Analogous to the ancient 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

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

- if passed, wait for this specific key, e.g. 'Q', 'ESC'. (keys) – 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 Windows API crud. Most of the time, it is not necessary to use this module directly; the detection module is 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.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

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.