Utilities

Command Output

pavilion.output.fprint(file, *args, color=None, bullet='', width=0, wrap_indent=0, sep=' ', end='\n', flush=False, clear=False)

Print with automatic wrapping, bullets, and other features. Also accepts all print() kwargs.

Parameters
  • args – Standard print function args

  • color (int) – ANSI color code to print with.

  • bullet (str) – Print the first line with this ‘bullet’ string, and the following lines indented to match.

  • sep (str) – The standard print sep argument.

  • file – Stream to print.

  • wrap_indent (int) – Indent lines (after the first) this number of spaces for each paragraph.

  • width (Union[int,None]) – Wrap the text to this width. If 0, find the terminal’s width and wrap to that.

  • end (str) – String appended after the last value (default n)

  • flush (bool) – Whether to forcibly flush the stream.

  • clear (bool) – Perform a ‘clear_line’ before printing.

pavilion.output.draw_table(outfile, fields, rows, field_info=None, border=False, pad=True, border_chars=None, header=True, title=None, table_width=None)

Prints a table from the given data, dynamically setting the column width.

Parameters
  • outfile – The file-like object to write to.

  • fields (list) – A list of the fields to include, in the given order. These also serve as the default column titles (Capitalized).

  • rows (list(dict)) – A list of data dictionaries. A None may be included to denote that a horizontal line row should be inserted.

  • field_info (dict) –

    Should be a dictionary of field names (all of

    which are optional) where the value is a dict of:

    • title - The column header for this field. Defaults to the field name, capitalized.

    • transform - a function that takes the field value, transforms it in some way, and returns the result to be inserted into the table.

    • format - a format string in the new style format syntax. It will expect the data for that row as arg 0. IE: ‘{0:2.2f}%’.

    • default - A default value for the field. A blank is printed by default.

    • no_wrap - a boolean that determines if a field will be wrapped or not.

    • max_width - the max width for a given field.

    • min_width - the min width for a given field.

  • border (bool) – Put a border around the table. Defaults False.

  • header (bool) – Print a header row of column names followed by a horizontal seperator. Defaults to True.

  • pad (bool) – Put a space on either side of each header and row entry. Default True.

  • border_chars (dict) – A dictionary of characters for drawing the table borders and separators. Expects the keys ‘vsep’, ‘hsep’, ‘isep’. By default these are ‘|’, ‘-’, and ‘+’.

  • title (str) – Add the given title above the table. Default None

  • table_width (int) – By default size table to the terminal width. If set size the table to this width instead.

Returns

None

Examples

A simple table:

from pavilion import utils

# The table data is expected as a list of dictionaries with identical keys.
# Not all dictionary fields will necessarily be used. Commands will
# typically generate the rows dynamically...
rows = [
    {'color': 'BLACK',  'code': 30, 'usage': 'Default'},
    {'color': 'RED',    'code': 31, 'usage': 'Fatal Errors'},
    {'color': 'GREEN',  'code': 32, 'usage': 'Warnings'},
    {'color': 'YELLOW', 'code': 33, 'usage': 'Discouraged'},
    {'color': 'BLUE',   'code': 34, 'usage': 'Info'}
]
# The data columns to print (and their default column labels).
columns = ['color', 'usage']

output.draw_table(
    outfile=sys.stdout,
    field_info={},

# Produces a table like this:
#
#  Color  | Usage
# --------+--------------
#  BLACK  | Default
#  RED    | Fatal Errors
#  GREEN  | Warnings
#  YELLOW | Discouraged
#  BLUE   | Info

A more complicated example:

from pavilion import utils
import sys

rows = [
    {'color': 'BLACK',   'code': 30, 'usage': 'Default'},
    {'color': 'RED',     'code': 31, 'usage': 'Fatal Errors'},
    {'color': 'GREEN',   'code': 32, 'usage': 'Warnings'},
    {'color': 'YELLOW',  'code': 33, 'usage': 'Discouraged'},
    {'color': 'BLUE',    'code': 34, 'usage': 'Info'},
    {'color': 'CYAN',    'code': 35},
    {'color': 'MAGENTA', 'code': 36},

]

columns = ['color', 'code', 'usage']
field_info = {
    # Colorize the color column with a transform function.
    'color': {
        'transform': lambda t: utils.ANSIString(t, utils.COLORS.get(t)),
    },
    # Format and add a better column header to the 'code' column.
    'code': {
        'title': 'ANSI Code',
        'format': '0x{0:x}',
    },
    # Put in a default for our missing usage values.
    # (The default is just to leave the column empty.)
    'usage': {
        'default': 'Whatever you want.'
    }
}

output.draw_table(
    outfile=sys.stdout,
    field_info=field_info,
    fields=columns,
    rows=rows,
    # Add a border. Why not?
    border=True,
    # No padding between the data and column seperators.
    pad=False,
    title="A Demo Table."
)

# Produces a table like this (plus with the color names in color):
#
# +-------+---------+------------------+
# | A Demo Table.                      |
# +-------+---------+------------------+
# |Color  |ANSI Code|Usage             |
# +-------+---------+------------------+
# |BLACK  |0x1e     |Default           |
# |RED    |0x1f     |Fatal Errors      |
# |GREEN  |0x20     |Warnings          |
# |YELLOW |0x21     |Discouraged       |
# |BLUE   |0x22     |Info              |
# |CYAN   |0x23     |Whatever you want.|
# |MAGENTA|0x24     |Whatever you want.|
# +-------+---------+------------------+
pavilion.output.dbg_print(*args, color=33, file=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, end='', pformat=True, **kwargs)

A colored print statement for debug printing. Use when you want to print dbg statements and easily excise it later.

Parameters
  • file – The file object to write to.

  • end – Default the ending to no newline (we do a pre-newline because of how unittest prints stuff.

  • color (int) – ANSI color code to print the string under.

  • pformat (bool) – Automatically apply pprint.pformat to args that are dicts or lists.

  • kwargs – Also accepts all print() kwargs.

Colorized Output

Both fprint() and dbg_print above take a ‘color’ argument, which allows you to colorize the output.

pavilion.output.COLORS

Available colors.

class pavilion.output.ANSIString(data, code=None)

Create a string with an implicit ANSI display mode. The ansi code will be used when the string is formatted.

hello = ANSIStr(“Hello World”, utils.RED) print(hello)

ivar data

The raw string data.

colorize()

Return the string wrapped in the appropriate ANSI escapes.

wrap(width=70)

Wrap the text as with textwrap, but return ANSIString objects with the same ANSI code applied.

JSON Output

pavilion.output.json_dump(obj, file, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw)

Dump data to string as per the json dumps function, but using our custom encoder.