terminal.py¶
Module containing Terminal
, the primary API entry point.
-
class
Terminal
(kind=None, stream=None, force_styling=False)[source]¶ An abstraction for color, style, positioning, and input in the terminal.
This keeps the endless calls to
tigetstr()
andtparm()
out of your code, acts intelligently when somebody pipes your output to a non-terminal, and abstracts over the complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across terminal types.Initialize the terminal.
Parameters: - kind (str) –
A terminal string as taken by
curses.setupterm()
. Defaults to the value of theTERM
environment variable.Note
Terminals withing a single process must share a common
kind
. See_CUR_TERM
. - stream (file) –
A file-like object representing the Terminal output. Defaults to the original value of
sys.__stdout__
, likecurses.initscr()
does.If
stream
is not a tty, empty Unicode strings are returned for all capability values, so things like piping your program output to a pipe or file does not emit terminal sequences. - force_styling (bool) –
Whether to force the emission of capabilities even if
sys.__stdout__
does not seem to be connected to a terminal. If you want to force styling to not happen, useforce_styling=None
.This comes in handy if users are trying to pipe your output through something like
less -r
or build systems which support decoding of terminal sequences.
-
__getattr__
(attr)[source]¶ Return a terminal capability as Unicode string.
For example,
term.bold
is a unicode string that may be prepended to text to set the video attribute for bold, which should also be terminated with the pairingnormal
. This capability returns a callable, so you can useterm.bold("hi")
which results in the joining of(term.bold, "hi", term.normal)
.Compound formatters may also be used. For example:
>>> term.bold_blink_red_on_green("merry x-mas!")
For a parameterized capability such as
move
(orcup
), pass the parameters as positional arguments:>>> term.move(line, column)
See the manual page terminfo(5) for a complete list of capabilities and their arguments.
-
location
(x=None, y=None)[source]¶ Context manager for temporarily moving the cursor.
Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:
term = Terminal() with term.location(2, 5): for x in xrange(10): print('I can do it %i times!' % x) print('We're back to the original location.')
Specify
x
to move to a certain column,y
to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement.Note
The store- and restore-cursor capabilities used internally provide no stack. This means that
location()
calls cannot be nested: only one should be entered at a time.
-
get_location
(timeout=None)[source]¶ Return tuple (row, column) of cursor position.
Parameters: timeout (float) – Return after time elapsed in seconds with value (-1, -1)
indicating that the remote end did not respond.Return type: tuple Returns: cursor position as tuple in form of (x, y)
.The location of the cursor is determined by emitting the
u7
terminal capability, or VT100 Query Cursor Position when such capability is undefined, which elicits a response from a reply string described by capabilityu6
, or again VT100’s definition of\x1b[%i%d;%dR
when undefined.The
(row, col)
return value matches the parameter order of themove
capability, so that the following sequence should cause the cursor to not move at all:>>> term = Terminal() >>> term.move(*term.get_location()))
Warning
You might first test that a terminal is capable of informing you of its location, while using a timeout, before later calling. When a timeout is specified, always ensure the return value is conditionally checked for
(-1, -1)
.
-
fullscreen
()[source]¶ Context manager that switches to secondary screen, restoring on exit.
Under the hood, this switches between the primary screen buffer and the secondary one. The primary one is saved on entry and restored on exit. Likewise, the secondary contents are also stable and are faithfully restored on the next entry:
with term.fullscreen(): main()
Note
There is only one primary and one secondary screen buffer.
fullscreen()
calls cannot be nested, only one should be entered at a time.
Context manager that hides the cursor, setting visibility on exit.
- with term.hidden_cursor():
- main()
Note
hidden_cursor()
calls cannot be nested: only one should be entered at a time.
-
move_xy
(x, y)[source]¶ A callable string that moves the cursor to the given
(x, y)
screen coordinates.Parameters: Return type: Returns: Callable string that moves the cursor to the given coordinates
-
move_yx
(y, x)[source]¶ A callable string that moves the cursor to the given
(y, x)
screen coordinates.Parameters: Return type: Returns: Callable string that moves the cursor to the given coordinates
-
move_left
¶ Move cursor 1 cells to the left, or callable string for n>1 cells.
-
move_right
¶ Move cursor 1 or more cells to the right, or callable string for n>1 cells.
-
move_up
¶ Move cursor 1 or more cells upwards, or callable string for n>1 cells.
-
move_down
¶ Move cursor 1 or more cells downwards, or callable string for n>1 cells.
-
color
¶ A callable string that sets the foreground color.
Return type: ParameterizingString The capability is unparameterized until called and passed a number, at which point it returns another string which represents a specific color change. This second string can further be called to color a piece of text and set everything back to normal afterward.
This should not be used directly, but rather a specific color by name or
color_rgb()
value.
-
color_rgb
(red, green, blue)[source]¶ Provides callable formatting string to set foreground color to the specified RGB color.
Parameters: Return type: Returns: Callable string that sets the foreground color
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm
.
-
on_color
¶ A callable capability that sets the background color.
Return type: ParameterizingString
-
on_color_rgb
(red, green, blue)[source]¶ Provides callable formatting string to set background color to the specified RGB color.
Parameters: Return type: Returns: Callable string that sets the foreground color
If the terminal does not support RGB color, the nearest supported color will be determined using
color_distance_algorithm
.
-
rgb_downconvert
(red, green, blue)[source]¶ Translate an RGB color to a color code of the terminal’s color depth.
Parameters: Return type: Returns: Color code of downconverted RGB color
-
normal
¶ A capability that resets all video attributes.
Return type: str normal
is an alias forsgr0
orexit_attribute_mode
. Any styling attributes previously applied, such as foreground or background colors, reverse video, or bold are reset to defaults.
-
stream
¶ Read-only property: stream the terminal outputs to.
This is a convenience attribute. It is used internally for implied writes performed by context managers
hidden_cursor()
,fullscreen()
,location()
, andkeypad()
.
-
number_of_colors
¶ Number of colors supported by terminal.
Common return values are 0, 8, 16, 256, or 1 << 24.
This may be used to test whether the terminal supports colors, and at what depth, if that’s a concern.
-
color_distance_algorithm
¶ Color distance algorithm used by
rgb_downconvert()
.The slowest, but most accurate, ‘cie2000’, is default. Other available options are ‘rgb’, ‘rgb-weighted’, ‘cie76’, and ‘cie94’.
-
ljust
(text, width=None, fillchar=' ')[source]¶ Left-align
text
, which may contain terminal sequences.Parameters: Return type: Returns: String of
text
, left-aligned bywidth
.
-
rjust
(text, width=None, fillchar=' ')[source]¶ Right-align
text
, which may contain terminal sequences.Parameters: Return type: Returns: String of
text
, right-aligned bywidth
.
-
center
(text, width=None, fillchar=' ')[source]¶ Center
text
, which may contain terminal sequences.Parameters: Return type: Returns: String of
text
, centered bywidth
-
length
(text)[source]¶ Return printable length of a string containing sequences.
Parameters: text (str) – String to measure. May contain terminal sequences. Return type: int Returns: The number of terminal character cells the string will occupy when printed Wide characters that consume 2 character cells are supported:
>>> term = Terminal() >>> term.length(term.clear + term.red(u'コンニチハ')) 10
Note
Sequences such as ‘clear’, which is considered as a “movement sequence” because it would move the cursor to (y, x)(0, 0), are evaluated as a printable length of 0.
-
strip
(text, chars=None)[source]¶ Return
text
without sequences and leading or trailing whitespace.Return type: str Returns: Text with leading and trailing whitespace removed >>> term.strip(u' \x1b[0;3m xyz ') u'xyz'
-
rstrip
(text, chars=None)[source]¶ Return
text
without terminal sequences or trailing whitespace.Return type: str Returns: Text with terminal sequences and trailing whitespace removed >>> term.rstrip(u' \x1b[0;3m xyz ') u' xyz'
-
lstrip
(text, chars=None)[source]¶ Return
text
without terminal sequences or leading whitespace.Return type: str Returns: Text with terminal sequences and leading whitespace removed >>> term.lstrip(u' \x1b[0;3m xyz ') u'xyz '
-
strip_seqs
(text)[source]¶ Return
text
stripped of only its terminal sequences.Return type: str Returns: Text with terminal sequences removed >>> term.strip_seqs(u'\x1b[0;3mxyz') u'xyz' >>> term.strip_seqs(term.cuf(5) + term.red(u'test')) u' test'
Note
Non-destructive sequences that adjust horizontal distance (such as
\b
orterm.cuf(5)
) are replaced by destructive space or erasing.
-
split_seqs
(text, **kwds)[source]¶ Return
text
split by individual character elements and sequences.Parameters: - text (str) – String containing sequences
- kwds – remaining keyword arguments for
re.split()
.
Return type: Returns: List of sequences and individual characters
>>> term.split_seqs(term.underline(u'xyz')) ['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
-
wrap
(text, width=None, **kwargs)[source]¶ Text-wrap a string, returning a list of wrapped lines.
Parameters: - text (str) – Unlike
textwrap.wrap()
,text
may contain terminal sequences, such as colors, bold, or underline. By default, tabs intext
are expanded bystring.expandtabs()
. - width (int) – Unlike
textwrap.wrap()
,width
will default to the width of the attached terminal. - kwargs – See
textwrap.TextWrapper
Return type: Returns: List of wrapped lines
See
textwrap.TextWrapper
for keyword arguments that can customize wrapping behaviour.- text (str) – Unlike
-
getch
()[source]¶ Read, decode, and return the next byte from the keyboard stream.
Return type: unicode Returns: a single unicode character, or u''
if a multi-byte sequence has not yet been fully received.This method name and behavior mimics curses
getch(void)
, and it supportsinkey()
, reading only one byte from the keyboard string at a time. This method should always return without blocking if called afterkbhit()
has returned True.Implementors of alternate input stream methods should override this method.
-
ungetch
(text)[source]¶ Buffer input data to be discovered by next call to
inkey()
.Parameters: text (str) – String to be buffered as keyboard input.
-
kbhit
(timeout=None)[source]¶ Return whether a keypress has been detected on the keyboard.
This method is used by
inkey()
to determine if a byte may be read usinggetch()
without blocking. The standard implementation simply uses theselect.select()
call on stdin.Parameters: timeout (float) – When timeout
is 0, this call is non-blocking, otherwise blocking indefinitely until keypress is detected when None (default). Whentimeout
is a positive number, returns aftertimeout
seconds have elapsed (float).Return type: bool Returns: True if a keypress is awaiting to be read on the keyboard attached to this terminal. When input is not a terminal, False is always returned.
-
cbreak
()[source]¶ Allow each keystroke to be read immediately after it is pressed.
This is a context manager for
tty.setcbreak()
.This context manager activates ‘rare’ mode, the opposite of ‘cooked’ mode: On entry,
tty.setcbreak()
mode is activated disabling line-buffering of keyboard input and turning off automatic echo of input as output.Note
You must explicitly print any user input you would like displayed. If you provide any kind of editing, you must handle backspace and other line-editing control functions in this mode as well!
Normally, characters received from the keyboard cannot be read by Python until the Return key is pressed. Also known as cooked or canonical input mode, it allows the tty driver to provide line-editing before shuttling the input to your program and is the (implicit) default terminal mode set by most unix shells before executing programs.
Technically, this context manager sets the
termios
attributes of the terminal attached tosys.__stdin__
.Note
tty.setcbreak()
setsVMIN = 1
andVTIME = 0
, see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
-
raw
()[source]¶ A context manager for
tty.setraw()
.Although both
break()
andraw()
modes allow each keystroke to be read immediately after it is pressed, Raw mode disables processing of input and output.In cbreak mode, special input characters such as
^C
or^S
are interpreted by the terminal driver and excluded from the stdin stream. In raw mode these values are receive by theinkey()
method.Because output processing is not done, the newline
'\n'
is not enough, you must also print carriage return to ensure that the cursor is returned to the first column:with term.raw(): print("printing in raw mode", end="\r\n")
-
keypad
()[source]¶ Context manager that enables directional keypad input.
On entrying, this puts the terminal into “keyboard_transmit” mode by emitting the keypad_xmit (smkx) capability. On exit, it emits keypad_local (rmkx).
On an IBM-PC keyboard with numeric keypad of terminal-type xterm, with numlock off, the lower-left diagonal key transmits sequence
\\x1b[F
, translated toTerminal
attributeKEY_END
.However, upon entering
keypad()
,\\x1b[OF
is transmitted, translating toKEY_LL
(lower-left key), allowing you to determine diagonal direction keys.
-
inkey
(timeout=None, esc_delay=0.35)[source]¶ Read and return the next keyboard event within given timeout.
Generally, this should be used inside the
raw()
context manager.Parameters: - timeout (float) – Number of seconds to wait for a keystroke before
returning. When
None
(default), this method may block indefinitely. - esc_delay (float) – To distinguish between the keystroke of
KEY_ESCAPE
, and sequences beginning with escape, the parameteresc_delay
specifies the amount of time after receiving escape (chr(27)
) to seek for the completion of an application key before returning aKeystroke
instance forKEY_ESCAPE
.
Return type: Returns: Keystroke
, which may be empty (u''
) iftimeout
is specified and keystroke is not received.Note
When used without the context manager
cbreak()
, orraw()
,sys.__stdin__
remains line-buffered, and this function will block until the return key is pressed!- timeout (float) – Number of seconds to wait for a keystroke before
returning. When
- kind (str) –
-
class
WINSZ
[source]¶ Structure represents return value of
termios.TIOCGWINSZ
.-
ws_row
¶ rows, in characters
-
ws_col
¶ columns, in characters
-
ws_xpixel
¶ horizontal size, pixels
-
ws_ypixel
¶ vertical size, pixels
Create new instance of WINSZ(ws_row, ws_col, ws_xpixel, ws_ypixel)
-
-
_CUR_TERM
= None¶