llnl.util.tty package


llnl.util.tty.colify module

Routines for printing columnar output. See colify() for more information.

class llnl.util.tty.colify.ColumnConfig(cols)

ベースクラス: object

llnl.util.tty.colify.colified(elts, **options)

Invokes the colify() function but returns the result as a string instead of writing it to an output string.

llnl.util.tty.colify.colify(elts, **options)

Takes a list of elements as input and finds a good columnization of them, similar to how gnu ls does. This supports both uniform-width and variable-width (tighter) columns.

If elts is not a list of strings, each element is first conveted using str().

  • output (stream) -- A file object to write to. Default is sys.stdout

  • indent (int) -- Optionally indent all columns by some number of spaces

  • padding (int) -- Spaces between columns. Default is 2

  • width (int) -- Width of the output. Default is 80 if tty not detected

  • cols (int) -- Force number of columns. Default is to size to terminal, or single-column if no tty

  • tty (bool) -- Whether to attempt to write to a tty. Default is to autodetect a tty. Set to False to force single-column output

  • method (str) -- Method to use to fit columns. Options are variable or uniform. Variable-width columns are tighter, uniform columns are all the same width and fit less data on the screen

llnl.util.tty.colify.colify_table(table, **options)

Version of colify() for data expressed in rows, (list of lists).

Same as regular colify but takes a list of lists, where each sub-list must be the same length, and each is interpreted as a row in a table. Regular colify displays a sequential list of values in columns.

llnl.util.tty.colify.config_uniform_cols(elts, console_width, padding, cols=0)

Uniform-width column fitting algorithm.

Determines the longest element in the list, and determines how many columns of that width will fit on screen. Returns a corresponding column config.

llnl.util.tty.colify.config_variable_cols(elts, console_width, padding, cols=0)

Variable-width column fitting algorithm.

This function determines the most columns that can fit in the screen width. Unlike uniform fitting, where all columns take the width of the longest element in the list, each column takes the width of its own longest element. This packs elements more efficiently on screen.

If cols is nonzero, force

llnl.util.tty.color module

This file implements an expression syntax, similar to printf, for adding ANSI colors to text.

See colorize(), cwrite(), and cprint() for routines that can generate colored output.

colorize will take a string and replace all color expressions with ANSI control codes. If the isatty keyword arg is set to False, then the color expressions will be converted to null strings, and the returned string will have no color.

cwrite and cprint are equivalent to write() and print() calls in python, but they colorize their output. If the stream argument is not supplied, they write to sys.stdout.

Here are some example color expressions:




Turn on red coloring


Turn on bright red coloring


Bold foo, but don't change text color


Underline bar, but don't change text color


Turn on bold, blue text


Turn on bright blue text with an underline


Revert to plain formatting


Print out 'green' in bold, green text, then reset to plain.


Print out 'green' in bold, green text, then reset to plain.

The syntax consists of:


'@' [style] color-code '{' text '}' | '@.' | '@@'


'*' | '_'





'@' indicates the start of a color expression. It can be followed by an optional * or _ that indicates whether the font should be bold or underlined. If * or _ is not provided, the text will be plain. Then an optional color code is supplied. This can be [krgybmcw] or [KRGYBMCW], where the letters map to black(k), red(r), green(g), yellow(y), blue(b), magenta(m), cyan(c), and white(w). Lowercase letters denote normal ANSI colors and capital letters denote bright ANSI colors.

Finally, the color expression can be followed by text enclosed in {}. If braces are present, only the text in braces is colored. If the braces are NOT present, then just the control codes to enable the color will be output. The console can be reset later to plain text with '@.'.

To output an @, use '@@'. To output a } inside braces, use '}}'.

exception llnl.util.tty.color.ColorParseError(message)

ベースクラス: Exception

Raised when a color format fails to parse.

class llnl.util.tty.color.ColorStream(stream, color=None)

ベースクラス: object

write(string, **kwargs)
writelines(sequence, **kwargs)

Escapes special characters needed for color codes.

Replaces the following symbols with their equivalent literal forms:






string (str) -- the string to escape


the string with color codes escaped




Length of extra color characters in a string


Return the length of a string, excluding ansi color sequences.


Context manager to temporarily use a particular color setting.

llnl.util.tty.color.colorize(string, **kwargs)

Replace all color expressions in a string with ANSI control codes.


string (str) -- The string to replace


The filtered string




color (bool) -- If False, output will be plain text without control codes, for output to non-console devices.

llnl.util.tty.color.cprint(string, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, color=None)

Same as cwrite, but writes a trailing newline to the stream.

llnl.util.tty.color.cwrite(string, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, color=None)

Replace all color expressions in string with ANSI control codes and write the result to the stream. If color is False, this will write plain text with no color. If True, then it will always write colored output. If not supplied, then it will be set based on stream.isatty().


Return whether commands should print color or not.

class llnl.util.tty.color.match_to_ansi(color=True)

ベースクラス: object


Returns a TTY escape sequence for a color


Set when color should be applied. Options are:

  • True or 'always': always print color

  • False or 'never': never print color

  • None or 'auto': only print color if sys.stdout is a tty.

llnl.util.tty.log module

Utility classes for logging the output of blocks of code.

class llnl.util.tty.log.Unbuffered(stream)

ベースクラス: object

Wrapper for Python streams that forces them to be unbuffered.

This is implemented by forcing a flush after each write.

class llnl.util.tty.log.keyboard_input(stream)

ベースクラス: object

Context manager to disable line editing and echoing.

Use this with sys.stdin for keyboard input, e.g.:

with keyboard_input(sys.stdin):
    r, w, x = select.select([sys.stdin], [], [])
    # ... do something with keypresses ...

This disables canonical input so that keypresses are available on the stream immediately. Typically standard input allows line editing, which means keypresses won't be sent until the user hits return.

It also disables echoing, so that keys pressed aren't printed to the terminal. So, the user can hit, e.g., 'v', and it's read on the other end of the pipe immediately but not printed.

When the with block completes, prior TTY settings are restored.

Note: this depends on termios support. If termios isn't available, or if the stream isn't a TTY, this context manager has no effect.

class llnl.util.tty.log.log_output(file_like=None, echo=False, debug=False, buffer=False)

ベースクラス: object

Context manager that logs its output to a file.

In the simplest case, the usage looks like this:

with log_output('logfile.txt'):
    # do things ... output will be logged

Any output from the with block will be redirected to logfile.txt. If you also want the output to be echoed to stdout, use the echo parameter:

with log_output('logfile.txt', echo=True):
    # do things ... output will be logged and printed out

And, if you just want to echo some stuff from the parent, use force_echo:

with log_output('logfile.txt', echo=False) as logger:
    # do things ... output will be logged

    with logger.force_echo():
        # things here will be echoed *and* logged

Under the hood, we spawn a daemon and set up a pipe between this process and the daemon. The daemon writes our output to both the file and to stdout (if echoing). The parent process can communicate with the daemon to tell it when and when not to echo; this is what force_echo does. You can also enable/disable echoing by typing 'v'.

We try to use OS-level file descriptors to do the redirection, but if stdout or stderr has been set to some Python-level file object, we use Python-level redirection instead. This allows the redirection to work within test frameworks like nose and pytest.


Context manager to force local echo, even if echo is off.

Module contents

class llnl.util.tty.SuppressOutput(msg_enabled=True, warn_enabled=True, error_enabled=True)

ベースクラス: object

Class for disabling output in a scope using 'with' keyword

llnl.util.tty.debug(message, *args, **kwargs)
llnl.util.tty.die(message, *args, **kwargs)
llnl.util.tty.error(message, *args, **kwargs)
llnl.util.tty.get_number(prompt, **kwargs)

Get a string timestamp

llnl.util.tty.get_yes_or_no(prompt, **kwargs)
llnl.util.tty.hline(label=None, **kwargs)

Draw a labeled horizontal line.

  • char (str) -- Char to draw the line with. Default '-'

  • max_width (int) -- Maximum width of the line. Default is 64 chars.

llnl.util.tty.info(message, *args, **kwargs)
llnl.util.tty.msg(message, *args, **kwargs)

Gives file and line frame 'countback' frames from the bottom


Gets the dimensions of the console: (rows, cols).

llnl.util.tty.verbose(message, *args, **kwargs)
llnl.util.tty.warn(message, *args, **kwargs)