API Reference

CS

Command sequences.

SGR

SGR attributes.

EraseMode

Mode parameter for erase().

erase

Erase all or part of line/screen (cursor position does not change).

move

Move the cursor.

home

Move the cursor to the top left corner of the screen.

clear

Clear screen.

hide_cursor

Hide the cursor.

nestable_save_pos_possible

Return if nestable save_pos() context is supported.

save_pos

Save the cursor position.

alternate_screen

Use the alternate screen buffer.

fg

Return SGR parameters for foreground color.

bg

Return SGR parameters for background color.

sgr_string

Build a string with SGR control sequences.

sgr_print

Print a string with SGR control sequences.

text

Return the plain text without the SGR control sequences.

len_diff

Return the difference between len(s) and len(text(s)).

set_attributes_delimiters

Set the delimiters for attributes.

parse

Parse the specification string.

class ansictrls.CS

The attributes of this class are control sequences. Most of them can take parameters. Their meaning and number is explained in the documentation of the attributes. The default value for ED, EL and SGR is 0. For the others it is 1.

The attributes support the modulo operator (%); the result is a str. The right operand can be a single value or a tuple of values. The attributes can also be used as strings which is the same as using an empty tuple with the % operator.

>>> CS.CUU % 3
'\x1b[3A'
>>> CS.CUP % (4, 2)
'\x1b[4;2H'
>>> CS.CUP % ()
'\x1b[H'
>>> str(CS.CUP)
'\x1b[H'
ICH

Insert N space characters

CUU

Move cursor N rows up

CUD

Move cursor N rows down

CUF

Move cursor N columns foreward

CUB

Move cursor N columns backward

CNL

Move cursor to beginning of line N rows down

CPL

Move cursor to beginning of line N rows up

CHA

Move cursor to column N in current row

CUP

Move cursor to the absolute position N,M (row N, column M)

CHT

Move cursor N tab stops forward

ED

Erase in display (cursor position does not change).

  • N=0: From cursor to end of screen

  • N=1: From cursor to beginning of screen

  • N=2: Entire screen

  • N=3: All lines in scrollback buffer

EL

Erase in line (cursor position does not change).

  • N=0: From cursor to end of line

  • N=1: From cursor to beginning of line

  • N=2: Entire line

IL

Insert N rows

DL

Delete N rows

DCH

Delete N characters

SU

Scroll page N rows up (add new lines at bottom)

SD

Scroll page N rows down (add new lines at top)

ECH

Erase N characters

CBT

Move cursor N tab stops backward

HPA

Move cursor to column N in current row

VPA

Move cursor to row N in current column

SGR

Select graphic rendition. This control sequence can take multiple parameters. It is more convenient to use the attributes of the SGR class.

SCP

Save cursor position

RCP

Restore cursor position

SCU

Show cursor

HCU

Hide cursor

EAS

Enable alternate screen buffer

DAS

Disable alternate screen buffer

RIS

Reset screen to initial state

class ansictrls.SGR

The attributes of this class are parameters for CS.SGR and the sgr_string() and sgr_print() functions. They support the ~ unary operator. For attributes like Bold this means that it will be switched off; for colors that bright colors are used.

Bold

Attribute bold

Faint

Attribute faint

Italic

Attribute italic

Underlined

Attribute underlined

Attribute blink

Inverse

Attribute inverse

Crossedout

Attribute crossedout

Overlined

Attribute overlined

Reset

Attribute reset

FgBlack

Foreground color black

FgRed

Foreground color red

FgGreen

Foreground color green

FgYellow

Foreground color yellow

FgBlue

Foreground color blue

FgMagenta

Foreground color magenta

FgCyan

Foreground color cyan

FgWhite

Foreground color white

FgDefault

Foreground color default

BgBlack

Background color black

BgRed

Background color red

BgGreen

Background color green

BgYellow

Background color yellow

BgBlue

Background color blue

BgMagenta

Background color magenta

BgCyan

Background color cyan

BgWhite

Background color white

BgDefault

Background color default

class ansictrls.EraseMode(value)

Mode parameter for erase().

SCRN_END = 0

From cursor to end of screen

SCRN_BEGIN = 1

From cursor to beginning of screen

SCRN_ALL = 2

Entire screen

SCRN_LINES = 3

All lines in scrollback buffer

LINE_END = 4

From cursor to end of line

LINE_BEGIN = 5

From cursor to beginning of line

LINE_ALL = 6

Entire line

ansictrls.erase(mode)

Erase all or part of line/screen (cursor position does not change).

Parameters

mode (EraseMode) – what to erase

ansictrls.move(row=0, col=0, rel=True)

Move the cursor.

The cursor can be moved relative (rel=True) or absolute (rel=False). If row=0 the cursor will be moved within the current row; if col=0 the cursor will be moved in the current column. Absolute row and col values start at 1 and cannot be negative. For relative movements negative numbers mean to the left or up and positive numbers move the cursor to the right or down. If only one of row or col is relative and the other is absolute, the rel parameter has to be a tuple: rel=(True, False) means relative row and absolute column movement and rel=(False, True) absolute row and relative column movement.

move(col=2)        # move cursor two columns to the right
                   # and leave the row unchanged
move(1, 1, False)  # move cursor to the top left corner
move(-5, 1, (True, False)  # move cursor to the beginning of the
                           # line five rows up
Parameters
  • row (int) – the row

  • col (int) – the column

  • rel (bool or tuple(bool, bool)) – if True the cursor will be moved relative to the current position

Raises
  • TypeError – if row or col are not of type int

  • ValueError – if not at least one of row or col is not 0, or if rel=False and row or col are negative

ansictrls.home()

Move the cursor to the top left corner of the screen.

ansictrls.clear(reset=False)

Clear screen.

Erase entire screen and move the cursor to the top left corner of the screen.

Parameters

reset (bool) – if set to True the line buffer will be erased too

ansictrls.hide_cursor()

Hide the cursor.

This function is a context manager for use in with statements. It hides the cursor when the context is entered and shows it again when the context is exited.

ansictrls.nestable_save_pos_possible()

Return if nestable save_pos() context is supported.

Returns

True if supported

Return type

bool

ansictrls.save_pos(nestable=False)

Save the cursor position.

This function is a context manager for use in with statements. It saves the cursor position when the context is entered and restores the cursor to the saved position when the context is exited.

If nestable=False the ANSI control sequences ESC[s: SCP - Save Cursor Position and ESC[u: RCP - Restore Cursor Position will be used. By doing so only the saved cursor position of the innermost context will be restored.

If nestable=True and nestable_save_pos_possible() returns True, each time the context is entered the position is determined by calling getyx() from the term package. If the terminal does not support the control sequence ESC[6n: DSR Device Status Report this is not possible.

Parameters

nestable (bool) – wether a nestable context should be used

Raises

RuntimeError – if nestable=True and nestable context not possible

ansictrls.alternate_screen()

Use the alternate screen buffer.

This function is a context manager for use in with statements. It switches to the alternate screen buffer when the context is entered and back to the normal screen buffer when the context is exited.

ansictrls.fg(*args)

Return SGR parameters for foreground color.

Parameters

args – arguments for color

Returns

color for use with CS.SGR or sgr_print()

ansictrls.bg(*args)

Return SGR parameters for background color.

Parameters

args – arguments for color

Returns

color for use with CS.SGR or sgr_print()

ansictrls.sgr_string(*args, reset=True)

Build a string with SGR control sequences.

Those arguments that are SGR attributes or the result of the fg() or bg() functions will be passed as parameters to CS.SGR, all others will be converted to strings. Than all elements will be concatenated and returned as a string.

>>> CS.SGR % (SGR.Bold, SGR.FgRed) + 'ABC' + CS.SGR % SGR.Reset
'\x1b[1;31mABC\x1b[0m'
>>> sgr_string(SGR.Bold, SGR.FgRed, 'ABC')
'\x1b[1;31mABC\x1b[0m'
Parameters
  • args – arguments

  • reset (bool) – if True all SGR attributes will be reset to normal at the end of the string

Returns

a string

Return type

str

ansictrls.sgr_print(*args, reset=True, end='\n', flush=False)

Print a string with SGR control sequences.

See function sgr_string().

Parameters
  • args – arguments (see: sgr_string())

  • reset (bool) – if True all SGR attributes will be reset to normal at the end of the string

  • end (str) – see built-in function print()

  • flush (bool) – see built-in function print()

ansictrls.text(s)

Return the plain text without the SGR control sequences.

Parameters

s (str) – the string with SGR control sequences

Returns

plain text

Return type

str

ansictrls.len_diff(s)

Return the difference between len(s) and len(text(s)).

Useful for adjusting the text on the screen:

s = sgr_string(SGR.Bold, SGR.FgRed, 'ABC')
w = 20
print(repr(s))
print(text(s))
print('1234567890' * 2)  # numbering 20 columns
print(s.center(w, '.'))
print(s.center(w + len_diff(s), '.'))
print('%*s' % (w, s))
print('%*s' % (w + len_diff(s), s))
print('{:.^{width}}'.format(s, width=w))
print('{:.^{width}}'.format(s, width=w + len_diff(s)))
'\x1b[1;31mABC\x1b[0m'
ABC
12345678901234567890
...ABC...
.........ABC........
      ABC
                 ABC
...ABC...
........ABC.........
Parameters

s (str) – the string with SGR control sequences

Returns

difference of the lengths of s and the visible text

Return type

int

ansictrls.set_attributes_delimiters(start='#[', end=']')

Set the delimiters for attributes.

See: specification string.

Parameters
  • start (str) – start delimiter

  • end (str) – end delimiter

Raises
  • TypeError – if one of the delimiters is not a string

  • ValueError – if one of the delimiters is an empty string

ansictrls.parse(spec, strict=False)

Parse the specification string.

Parameters
  • spec (str) – the specification string

  • strict (bool) – if False unknown attributes will be ignored

Returns

string with SGR control sequences

Return type

str

Raises

ValueError – if strict=True and an unkown attribute is encountered