console package

Module contents

console - Comprehensive utility library for ANSI terminals.
© 2018, Mike Miller - Released under the LGPL, version 3+.
console.set_debug_mode(value)[source]

Provides for more detailed output via logging functionality.

Submodules

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'

12 014 0x0C ^L Formfeed (also – New page NP)

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

Sequence terminator, (ESC precedes)

console.constants.VT = '\x0b'

11 013 0x0B ^K Vertical TAB

console.core module

Complicated Gobbyldegook supporting the simple 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.detection module

This module contains capability detection routines for use under ANSI compatible terminals.

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.

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)
    return sys.stdin.read(1)
console.detection.choose_palette(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, basic_palette=None)[source]

Make a best effort to automatically determine whether to enable ANSI sequences, and if so, which color palettes are available.

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

Takes the following factors into account:

  • Whether output stream is a TTY.
  • TERM, ANSICON environment variables
  • CLICOLOR, NO_COLOR environment variables
Parameters:
  • stream – Which output file to check: stdout, stderr
  • basic_palette – Force the platform-dependent 16 color palette, for testing. List of 16 rgb-int tuples.
Returns:

‘basic’, ‘extended’, or ‘truecolor’

Return type:

None, str

console.detection.color_is_allowed()[source]

Look for clues in environment, e.g.:

Returns:Allowed
Return type:Bool
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 to check for equality, i.e. MYAPP_COLOR_FORCED='1'
Returns:Forced
Return type:Bool
console.detection.detect_palette_support(basic_palette=None)[source]

Returns whether we think the terminal supports basic, extended, or truecolor. None if not able to tell.

Returns:‘basic’, ‘extended’, ‘truecolor’
Return type:None or str
console.detection.detect_unicode_support()[source]

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

Experimental, implementation idea is from the link below:
https://unix.stackexchange.com/questions/184345/detect-how-much-of-unicode-my-terminal-supports-even-through-screen

Todo

needs improvement. # should return None or True on redirection?

Returns:Boolean | None if not a TTY
console.detection.get_available_palettes(chosen_palette)[source]

Given a chosen palette, returns tuple of those available, or None when not found.

Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes.

Returns:is tty or None if not found.
Return type:Boolean, None
console.detection.get_color(name, number=None)[source]

Query the default terminal, for colors, etc.

Direct queries supported on xterm, iTerm, perhaps others.

Parameters:
  • str – name, one of (‘foreground’, ‘fg’, ‘background’, ‘bg’, or ‘index’) # index grabs a palette index
  • int – or a “dynamic color number of (4, 10-19),” see links below.
  • str – number - if name is index, number should be an int from 0…255

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 if needed:

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

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

Return type:tuple[int]

Examples

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

Note

Blocks if terminal does not support the function. Checks is_a_tty() first, since function would also block if i/o were redirected through a pipe.

On Windows, only able to find palette defaults, which may be different if they were customized. To find the palette index instead, see windows.get_color.

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)

TODO: needs non-ansi mode for Windows .. note:

Checks is_a_tty() first, since function would block if i/o were
redirected through a pipe.
console.detection.get_size(fallback=(80, 24))[source]

Convenience copy of shutil.get_terminal_size.

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

Checks system for 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

Experimental, few terms outside xterm support this correctly. MATE Terminal returns “Terminal”. iTerm returns “”.

console.detection.load_x11_color_map(paths=('/etc/X11/rgb.txt', '/usr/share/X11/rgb.txt', '/usr/local/lib/X11/rgb.txt', '/usr/X11R6/lib/X11/rgb.txt'))[source]

Load and parse X11’s rgb.txt.

Loads:
x11_color_map: { name_lower: (‘R’, ‘G’, ‘B’) }
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_bin

Collection that returns empties as attributes.

console.proximity module

console.proximity

Given an 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.
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 move the cursor around, and manage terminal screens.

Context-managers with contextlib derived from:

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(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, **kwargs)[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'
bracketedpaste_disable = '\x1b[?2004l'
bracketedpaste_enable = '\x1b[?2004h'
cha = 'G'
cnl = 'E'
cpl = 'F'
cub = 'D'
cud = 'B'
cuf = 'C'
cup = ('H', '%d;%d')
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', '%d;%d')
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', '%d;%d')
mv2 = ('f', '%d;%d')
mv_x = 'G'
mv_y = 'd'
next_line = 'E'
prev_line = 'F'
rcp = '\x1b[u'
reset = '\x1bc'
rest_pos = '\x1b8'
rest_pos2 = '\x1b[u'
restore_title = ('t', '23;%d')
right = 'C'
save_pos = '\x1b7'
save_pos2 = '\x1b[s'
save_title = ('t', '22;%d')
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(x11_rgb_path=('/etc/X11/rgb.txt', '/usr/share/X11/rgb.txt', '/usr/local/lib/X11/rgb.txt', '/usr/X11R6/lib/X11/rgb.txt'), downgrade_method='euclid', **kwargs)[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
  • - '/path/to/X11/rgb.txt', (x11_rgb_filename) – defaults to a platform dependent value.
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(**kwargs)[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
b = 1
bold = 1
conceal = 8
crossed = 9
default = 0
dim = 2
encircle = 52
end = 0
font10 = 10
font11 = 11
font12 = 12
font13 = 13
font14 = 14
font15 = 15
font16 = 16
font17 = 17
font18 = 18
font19 = 19
font20 = 20
fraktur = 20
frame = 51
hide = 8
i = 3
italic = 3
overline = 53
primary = 10
reverse = 7
s = 9
strike = 9
u = 4
underline = 4
class console.style.EffectsTerminator(**kwargs)[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
b = 21
bg = 49
bold = 21
crossed = 29
default = 0
encircle = 54
end = 0
fg = 39
font = 23
frame = 54
i = 23
ideogram = 65
intensity = 22
italic = 23
overline = 55
reveal = 28
reverse = 27
s = 29
strike = 29
u = 24
underline = 24
class console.style.ForegroundPalette(x11_rgb_path=('/etc/X11/rgb.txt', '/usr/share/X11/rgb.txt', '/usr/local/lib/X11/rgb.txt', '/usr/X11R6/lib/X11/rgb.txt'), downgrade_method='euclid', **kwargs)[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
  • - '/path/to/X11/rgb.txt', (x11_rgb_filename) – defaults to a platform dependent value.
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

console.test_suite module

Testen-Sie, bitte.

console.utils module

This module contains utility and convenience functions for use under ANSI compatible terminals.

See also

console.utils.clear(mode=2)

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

Parameters:mode
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).
console.utils.clear_line(mode=2)[source]

Clear the current line.

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

Note

Cursor position does not change.

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

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

Parameters:mode
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).
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.len_stripped(text)[source]

Return the length of a string minus its ANSI escape sequences.

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

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

Analogous to the ancient DOS pause command, with a modifiable message.

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_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
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
  • osc – bool - include OSC commands in the strippage.
  • c1 – bool - include C1 commands in the strippage.

Notes

Enabling c1 and osc stripping is less efficient and the two options can mildly conflict with one another. The less problematic order was chosen, so 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. “Where’s the any key?”

Parameters:- if passed, wait for this specific key, e.g. 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.

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.enable_vt_processing()[source]

What it says on the tin.

Returns:Tuple of status codes from SetConsoleMode for (stdout, stderr).
console.windows.get_color(name, stream=-11)[source]

Returns current colors 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 from the conhost palette.

Ids under 0x8 (8) are dark colors, above light.

Return type:

int

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

Returns current position of cursor, starts at 1.

console.windows.get_title()[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_initialized()[source]
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.