console Package¶
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!
-
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 better illustrate relationships between characters and control codes:
To find the binary representation of a character, concatenate the two digit group code above its column, with its five digit row code:
- [3mOptional 8th bit[0m → [32m0[0m [1;32m10[0m [32m01000[0m ⇒ [32m0[1;32m10[0m[32m01000[0m
[3mGroup code[0m ↗ ↑ [3mRow code[0m ↑ [3mFull byte, aka “H”[0m
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 bits to zero. This is why, for example:
[3mBEL[0m, the Bell may be activated with [7m^G[0m [3m(column to right)[0m
[3mBS[0m, the Backspace key is represented by [7m^H[0m
[3mESC[0m, the Escape key is represented by [7m^[[0m etc.
This is also why one can add 32/20h to the index of a capital to find the corresponding lower case letter.
- Parameters
Add hyperlinks to special characters. (link) –
Skip informative headers. (no-headers) –
Use symbols instead of names for control-chars. (unicode_symbols) –
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
(**kwargs)¶ Simple system beep for POSIX terminals, may be disabled.
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)[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.cli module¶
Convenience command-line interface script for select utility functions and methods that don’t have common implementations, such as tput. (Optional arguments may be shortened and are recognized when unique.)
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.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. 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:rgb:DEAD/BEEF/CAFE
- 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)[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().
- 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 variablesAre 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.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.
-
console.disabled.
empty_bin
¶ Collection that returns EmptyAttributes on any attribute access.
-
console.disabled.
empty_scr_bin
¶ Collection that returns EmptyAttributes on any attribute access.
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)[source]¶ Bases:
enum.Enum
An enumeration.
-
DOUBLE
= 3¶
-
FIGLET
= 2¶
-
NORMAL
= 1¶
-
-
class
console.viewers.
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’
-
tokens
= []¶
-
-
class
console.viewers.
StringCache
(palette, **kwargs)[source]¶ Bases:
dict
Used to cache rendered ANSI color/fx strings with a dictionary lookup interface.
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
= '\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.
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 – 99 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¶
-
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 = 99, width=32, debug=False)[source]¶ Convenience function for building a one-off progress bar, for scripts and CLI, etc.
- Parameters
The current value. (value) –
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 – 99 Set the total number of items
width – 32 Full width of bar, padding, and labels
Note
The value parameter is 0-based, therefore think 0-99, rather than 1-100. 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:
console.screen._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) '[7;4H' # 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:
console.screen._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) '[7;4H' # 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)
-
static
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:
ANSI escape codes and section 5:
-
class
console.style.
BackgroundPalette
(color_sep=None, 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
-
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:
console.core._MonochromePaletteBuilder
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, 22)¶
-
blink
= (5, 25)¶
-
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)¶
-
fastblink
= (6, 25)¶
-
frame
= (51, 54)¶
-
hide
= (8, 28)¶
-
i
= (3, 23)¶
-
italic
= (3, 23)¶
-
overline
= (53, 55)¶
-
reverse
= (7, 27)¶
-
s
= (9, 29)¶
-
slowblink
= (5, 25)¶
-
strike
= (9, 29)¶
-
u
= (4, 24)¶
-
underline
= (4, 24)¶
-
class
console.style.
EffectsTerminator
(color_sep=None, level=Ellipsis)[source]¶ Bases:
console.core._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
- Attempt to detect palette support. (autodetect) –
- If autodetect disabled, set palette support (palettes) – explicitly. str, seq, or None
-
b
= 22¶
-
bg
= 49¶
-
blink
= 25¶
-
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:
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
-
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:
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. 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.
-
console.utils.
make_hyperlink
(target, caption=None, icon='', _max_url_len=2083, _max_val_len=250, **params)[source]¶ 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_val_len (_max_url_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
A character or short string to repeat. (string) –
A color name to assign to the line, defaults to dim. (color) –
How long the line should be in characters, (width) – defaults (zero) to full width of terminal.
If a specific width is given, center it between spaces. (center) –
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
The text to change size. (text) –
Use the double-sized font. (double) –
Use the double-wide font. (wide) –
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
The number to start with, e.g. 0 or 1 (start) –
The column to limit to or end at. (limit) –
Number of spaces to push to the right. (offset) –
Whether to insert newlines after each line. (newlines) – 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.
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 title1 | ‘icon’ - Set only icon/taskbar title2 | ‘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.windows module¶
Module for traditional Windows API crud (though not WSL). Typically, it is not necessary to use this module directly; the detection module is preferred.
https://docs.microsoft.com/en-us/windows/console/console-reference
-
console.windows.
add_os_sysexits
()[source]¶ Make the sysexit.h exit-status constants available under Windows.
-
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.
https://docs.microsoft.com/en-us/windows/console/setconsolemode #ENABLE_VIRTUAL_TERMINAL_PROCESSING
- Returns
Tuple of status codes from SetConsoleMode for (stdout, stderr).
-
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_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.