Skip to main content

ANSI formatted terminal output toolset

Project description

pytermor

(yet another) Python library designed for formatting terminal output using ANSI escape codes. Implements automatic "soft" format termination. Provides a registry of ready-to-use SGR sequences and formats (=combined sequences).

Motivation

Key feature of this library is providing necessary abstractions for building complex text sections with lots of formatting, while keeping the application code clear and readable.

Installation

pip install pytermor

Use cases

Format is a combination of two control sequences; it wraps specified string with pre-defined leading and trailing SGR definitions.

from pytermor import fmt

print(fmt.blue('Use'), fmt.cyan('cases'))
Examples (click)

* image

Preset formats can safely overlap with each other (as long as they belong to different modifier groups).

from pytermor import fmt

print(fmt.blue(fmt.underlined('Nested') + fmt.bold(' formats')))

* image

Built-in automatic content-aware format termination.

from pytermor import autof

fmt1 = autof('hi_cyan', 'bold')
fmt2 = autof('bg_black', 'inversed', 'underlined', 'italic')

msg = fmt1(f'Content{fmt2("-aware format")} nesting')
print(msg)

* image

Create your own SGR sequences with build() method, which accepts color/attribute keys, integer codes and even existing SGRs, in any amount and in any order. Key resolving is case-insensitive.

from pytermor import seq, build

seq1 = build('red', 1)  # keys or integer codes
seq2 = build(seq1, seq.ITALIC)  # existing SGRs as part of a new one
seq3 = build('underlined', 'YELLOW')  # case-insensitive

msg = f'{seq1}Flexible{seq.RESET} ' + \
      f'{seq2}sequence{seq.RESET} ' + \
      str(seq3) + 'builder' + str(seq.RESET)
print(msg)

* image

Use build_c256() to set text/background color to any of ↗ xterm-256 colors.

from pytermor import build, build_c256
from pytermor import seq

txt = '256 colors support'
msg = f'{build("bold")}'
start_color = 41
for idx, c in enumerate(range(start_color, start_color+(36*6), 36)):
    msg += f'{build_c256(c)}'
    msg += f'{txt[idx*3:(idx+1)*3]}{seq.COLOR_OFF}'
print(msg)

* image

It's also possible to use 16M-color mode (or True color) — with build_rgb() wrapper method.

from pytermor import build, build_rgb
from pytermor import seq

txt = 'True color support'
msg = f'{build("bold")}'
for idx, c in enumerate(range(0, 256, 256//18)):
    msg += f'{build_rgb(max(0, 255-c), max(0, min(255, 127-(c*2))), c)}'
    msg += f'{txt[idx:(idx+1)]}{seq.COLOR_OFF}'
print(msg)

Format soft reset

There are two ways to manage text color and attribute termination:

  • hard reset (SGR 0 | \e[m)
  • soft reset (SGR 22, 23, 24 etc.)

The main difference between them is that hard reset disables all formatting after itself, while soft reset disables only actually necessary attributes (i.e. used as opening sequence in Format instance's context) and keeps the other.

That's what Format class and autof method are designed for: to simplify creation of soft-resetting text spans, so that developer doesn't have to restore all previously applied formats after every closing sequence.

Example: we are given a text span which is initially bold and underlined. We want to recolor a few words inside of this span. By default this will result in losing all the formatting to the right of updated text span (because RESET|\e[m clears all text attributes).

However, there is an option to specify what attributes should be disabled or let the library do that for you:

from pytermor import seq, fmt, autof
from pytermor.fmt import Format

# automatically:
fmt_warn = autof(seq.HI_YELLOW + seq.UNDERLINED)
# or manually (that's what autof() would do):
fmt_warn = Format(
    seq.HI_YELLOW + seq.UNDERLINED,  # sequences can be summed up, remember?
    seq.COLOR_OFF + seq.UNDERLINED_OFF,  # "counteractive" sequences
    hard_reset_after=False
)

orig_text = fmt.bold(f'{seq.BG_BLACK}this is the original string{seq.RESET}')
updated_text = orig_text.replace('original', fmt_warn('updated'), 1)
print(orig_text, '\n', updated_text)

image

As you can see, the update went well — we kept all the previously applied formatting. Of course, this method cannot be 100% applicable — for example, imagine that original text was colored blue. After the update "string" word won't be blue anymore, as we used COLOR_OFF escape sequence to neutralize our own yellow color. But it still can be helpful for a majority of cases (especially when text is generated and formatted by the same program and in one go).

API: [pytermor]

autof

Signature: autof(*params str|int|SequenceSGR) -> Format

Create new Format with specified control sequence(s) as a opening/starter sequence and automatically compose closing sequence that will terminate attributes defined in opening sequence while keeping the others (soft reset).

Resulting sequence params' order is the same as argument's order.

Each sequence param can be specified as:

  • string key (see API: Registries)
  • integer param value
  • existing SequenceSGR instance (params will be extracted)

build

Signature: build(*params str|int|SequenceSGR) -> SequenceSGR

Create new SequenceSGR with specified params. Resulting sequence params order is the same as argument order. Parameter specification is the same as for autof.

build_c256

Signature:build_c256(color: int, bg: bool = False) -> SequenceSGR

Create new SequenceSGR that sets text color or background color, depending on bg value, in 256-color mode. Valid values for color are [0; 255], see more at ↗ xterm-256 colors page.

build_rgb

Signature:build_rgb(r: int, g: int, b: int, bg: bool = False) -> SequenceSGR

Create new SequenceSGR that sets text color or background color, depending on bg value, in 16M-color mode. Valid values for r, g and b are [0; 255]; this range is linearly translated into [0x00; 0xFF] for each channel; the result value is composed as #RRGGBB.

API: SequenceSGR

Class representing SGR-mode ANSI escape sequence with varying amount of parameters.

Creating the sequence

You can use any of predefined sequences from pytermor.seq or create your own via standard constructor. Argument values as well as preset constants are described in API: Registries section.

from pytermor.seq import SequenceSGR

seq = SequenceSGR(4, 7)
...

Applying the sequence

To get the resulting sequence chars cast instance to str:

...
msg = f'({seq})'
print(msg + f'{SequenceSGR(0)}', str(msg.encode()), msg.encode().hex(':'))

image

1st part is "applied" escape sequence; 2nd part shows up a sequence in raw mode, as if it was ignored by the terminal; 3rd part is hexademical sequence byte values.

SGR sequence structure (click)
  1. \x1b|1b is ESC control character, which opens a control sequence.

  2. [ is sequence introducer, it determines the type of control sequence (in this case it's CSI, or "Control Sequence Introducer").

  3. 4 and 7 are parameters of the escape sequence; they mean "underlined" and "inversed" attributes respectively. Those parameters must be separated by ;.

  4. m is sequence terminator; it also determines the sub-type of sequence, in our case SGR, or "Select Graphic Rendition". Sequences of this kind are most commonly encountered.

Combining SGRs

One instance of SequenceSGR can be added to another. This will result in a new SequenceSGR with combined params.

from pytermor.seq import SequenceSGR
from pytermor import seq

combined = SequenceSGR(1, 31) + SequenceSGR(4)
print(f'{combined}combined{seq.RESET}', str(combined).encode())

image

API: Format

Format is a wrapper class that contains starting (i.e. opening) SequenceSGR and (optionally) closing SequenceSGR.

Creating the format

You can define your own reusable Formats or import predefined ones from pytermor.fmt (see API: Registries section).

from pytermor.fmt import Format
from pytermor import seq, fmt

fmt_error = Format(seq.BG_HI_RED + seq.UNDERLINED, seq.BG_COLOR_OFF + seq.UNDERLINED_OFF)
...

Applying the format

Use invoke() method of Format instance or call the instance itself to enclose specified string in starting/terminating SGR sequences:

...
msg = fmt.italic.invoke('italic might ' + fmt_error('not') + ' work')
print(msg)

image

API: StringFilter

Common string modifier interface with dynamic configuration support.

Subclasses

  • ReplaceSGR
  • ReplaceCSI
  • ReplaceNonAsciiBytes

Standalone usage

Can be executed using .invoke() method or with direct call.

from pytermor.util import ReplaceSGR
from pytermor import fmt

formatted = fmt.red('this text is red')
replaced = ReplaceSGR('[LIE]').invoke(formatted)
# replaced = ReplaceSequenceSGRs('[LIE]')(formatted)

print(formatted, '\n', replaced)

image

Usage with helper

Helper function apply_filters accepts both StringFilter (and subclasses) instances and subclasses' types, but latter is not configurable and will be invoked using default settings.

from pytermor.util import apply_filters, ReplaceNonAsciiBytes

ascii_and_binary = b'\xc0\xff\xeeQWE\xffRT\xeb\x00\xc0\xcd\xed'
# result = apply_filters(ascii_and_binary, ReplaceNonAsciiBytes(b'.'))
result = apply_filters(ascii_and_binary, ReplaceNonAsciiBytes)
print(ascii_and_binary, '\n', result)

image

API: Registries

Sequences (click)
  • code — SGR integer code(s) for specified sequence (order is important)
  • name — variable name; usage: from pytermor.seq import RESET
  • key — string that will be recognised by build()|autof() etc.
  • comment — effect of applying the sequence / additional notes

As a rule of a thumb, key equals to name in lower case.

code name key comment G
0 RESET reset Reset all attributes and colors B
1 BOLD bold A T T R I B U T E S
2 DIM dim
3 ITALIC italic
4 UNDERLINED underlined
5 BLINK_SLOW blink_slow
6 BLINK_FAST blink_fast
7 INVERSED inversed
8 HIDDEN hidden
9 CROSSLINED crosslined
21 DOUBLE_UNDERLINED double_underlined
53 OVERLINED overlined
22 BOLD_DIM_OFF bold_dim_off Special aspects... It's impossible to disable them separately. B R E A K E R S
23 ITALIC_OFF italic_off
24 UNDERLINED_OFF underlined_off
25 BLINK_OFF blink_off
27 INVERSED_OFF inversed_off
28 HIDDEN_OFF hidden_off
29 CROSSLINED_OFF crosslined_off
39 COLOR_OFF color_off Reset text color
49 BG_COLOR_OFF bg_color_off Reset bg color
55 OVERLINED_OFF overlined_off
30 BLACK black ﹇ T E X T ﹈ C O L O R S
31 RED red
32 GREEN green
33 YELLOW yellow
34 BLUE blue
35 MAGENTA magenta
36 CYAN cyan
37 WHITE white
38;5 Use color_c256() instead Set text color [256 mode]
38;2 Use color_rgb() instead Set text color [16M mode]
40 BG_BLACK bg_black B G

C O L O R S
41 BG_RED bg_red
42 BG_GREEN bg_green
43 BG_YELLOW bg_yellow
44 BG_BLUE bg_blue
45 BG_MAGENTA bg_magenta
46 BG_CYAN bg_cyan
47 BG_WHITE bg_white
48;5 Use color_c256() instead Set bg color [256 mode]
48;2 Use color_rgb() instead Set bg color [16M mode]
90 GRAY gray H I ﹇ T E X T ﹈ C O L O R S
91 HI_RED hi_red
92 HI_GREEN hi_green
93 HI_YELLOW hi_yellow
94 HI_BLUE hi_blue
95 HI_MAGENTA hi_magenta
96 HI_CYAN hi_cyan
97 HI_WHITE hi_white
100 BG_GRAY bg_gray H I

B G

C O L O R S
101 BG_HI_RED bg_hi_red
102 BG_HI_GREEN bg_hi_green
103 BG_HI_YELLOW bg_hi_yellow
104 BG_HI_BLUE bg_hi_blue
105 BG_HI_MAGENTA bg_hi_magenta
106 BG_HI_CYAN bg_hi_cyan
107 BG_HI_WHITE bg_hi_white

Formats (click)
  • name — variable name; usage: from pytermor.fmt import bold
  • opening seq, closing seq — corresponding SGRs

As a rule of a thumb, name equals to opening seq in lower case.

name opening seq closing seq G
bold BOLD BOLD_DIM_OFF A T T R I B U T E S
dim DIM BOLD_DIM_OFF
italic ITALIC ITALIC_OFF
underlined UNDERLINED UNDERLINED_OFF
inversed INVERSED INVERSED_OFF
overlined OVERLINED OVERLINED_OFF
red RED COLOR_OFF ﹇ T E X T ﹈ C O L O R S
green GREEN COLOR_OFF
yellow YELLOW COLOR_OFF
blue BLUE COLOR_OFF
magenta MAGENTA COLOR_OFF
cyan CYAN COLOR_OFF
bg_red BG_RED BG_COLOR_OFF B G

C O L O R S
bg_green BG_GREEN BG_COLOR_OFF
bg_yellow BG_YELLOW BG_COLOR_OFF
bg_blue BG_BLUE BG_COLOR_OFF
bg_magenta BG_MAGENTA BG_COLOR_OFF
bg_cyan BG_CYAN BG_COLOR_OFF

References

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytermor-1.1.0.tar.gz (18.3 kB view hashes)

Uploaded Source

Built Distribution

pytermor-1.1.0-py3-none-any.whl (14.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page