API

Tabular Output

CLI Helper’s tabular output module makes it easy to format your data using various formatting libraries.

When formatting data, you’ll primarily use the format_output() function and TabularOutputFormatter class.

cli_helpers.tabular_output.format_output(data, headers, format_name, **kwargs)[source]

Format output using format_name.

This is a wrapper around the TabularOutputFormatter class.

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • format_name (str) – The display format to use.
  • **kwargs – Optional arguments for the formatter.
Returns:

The formatted data.

Return type:

str

class cli_helpers.tabular_output.TabularOutputFormatter(format_name=None)[source]

An interface to various tabular data formatting libraries.

The formatting libraries supported include:
Parameters:format_name (str) – An optional, default format name.

Usage:

>>> from cli_helpers.tabular_output import TabularOutputFormatter
>>> formatter = TabularOutputFormatter(format_name='simple')
>>> data = ((1, 87), (2, 80), (3, 79))
>>> headers = ('day', 'temperature')
>>> print(formatter.format_output(data, headers))
  day    temperature
-----  -------------
    1             87
    2             80
    3             79

You can use any iterable for the data or headers:

>>> data = enumerate(('87', '80', '79'), 1)
>>> print(formatter.format_output(data, headers))
  day    temperature
-----  -------------
    1             87
    2             80
    3             79
format_name

The current format name.

This value must be in supported_formats.

format_output(data, headers, format_name=None, preprocessors=(), column_types=None, **kwargs)[source]

Format the headers and data using a specific formatter.

format_name must be a supported formatter (see supported_formats).

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • format_name (str) – The display format to use (optional, if the TabularOutputFormatter object has a default format set).
  • preprocessors (tuple) – Additional preprocessors to call before any formatter preprocessors.
  • **kwargs – Optional arguments for the formatter.
Returns:

The formatted data.

Return type:

str

Raises:

ValueError – If the format_name is not recognized.

classmethod register_new_formatter(format_name, handler, preprocessors=(), kwargs=None)[source]

Register a new output formatter.

Parameters:
  • format_name (str) – The name of the format.
  • handler (callable) – The function that formats the data.
  • preprocessors (tuple) – The preprocessors to call before formatting.
  • kwargs (dict) – Keys/values for keyword argument defaults.
supported_formats

The names of the supported output formats in a tuple.

Preprocessors

These preprocessor functions are used to process data prior to output.

cli_helpers.tabular_output.preprocessors.align_decimals(data, headers, column_types=(), **_)[source]

Align numbers in data on their decimal points.

Whitespace padding is added before a number so that all numbers in a column are aligned.

Outputting data before aligning the decimals:

1
2.1
10.59

Outputting data after aligning the decimals:

 1
 2.1
10.59
Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • column_types (iterable) – The columns’ type objects (e.g. int or float).
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.bytes_to_string(data, headers, **_)[source]

Convert all data and headers bytes to strings.

Binary data that cannot be decoded is converted to a hexadecimal representation via binascii.hexlify().

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.convert_to_string(data, headers, **_)[source]

Convert all data and headers to strings.

Binary data that cannot be decoded is converted to a hexadecimal representation via binascii.hexlify().

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.format_numbers(data, headers, column_types=(), integer_format=None, float_format=None, **_)[source]

Format numbers according to a format specification.

This uses Python’s format specification to format numbers of the following types: int, long (Python 2), float, and Decimal. See the Format Specification Mini-Language for more information about the format strings.

Note

A column is only formatted if all of its values are the same type (except for None).

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • column_types (iterable) – The columns’ type objects (e.g. int or float).
  • integer_format (str) – The format string to use for integer columns.
  • float_format (str) – The format string to use for float columns.
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.override_missing_value(data, headers, missing_value='', **_)[source]

Override missing values in the data with missing_value.

A missing value is any value that is None.

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • missing_value – The default value to use for missing data.
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.quote_whitespaces(data, headers, quotestyle="'", **_)[source]

Quote leading/trailing whitespace in data.

When outputing data with leading or trailing whitespace, it can be useful to put quotation marks around the value so the whitespace is more apparent. If one value in a column needs quoted, then all values in that column are quoted to keep things consistent.

Note

string.whitespace is used to determine which characters are whitespace.

Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • quotestyle (str) – The quotation mark to use (defaults to ').
Returns:

The processed data and headers.

Return type:

tuple

cli_helpers.tabular_output.preprocessors.style_output(data, headers, style=None, header_token='Token.Output.Header', odd_row_token='Token.Output.OddRow', even_row_token='Token.Output.EvenRow', **_)[source]

Style the data and headers (e.g. bold, italic, and colors)

Note

This requires the Pygments library to be installed. You can install it with CLI Helpers as an extra:

$ pip install cli_helpers[styles]

Example usage:

from cli_helpers.tabular_output.preprocessors import style_output
from pygments.style import Style
from pygments.token import Token

class YourStyle(Style):
    default_style = ""
    styles = {
        Token.Output.Header: 'bold #ansired',
        Token.Output.OddRow: 'bg:#eee #111',
        Token.Output.EvenRow: '#0f0'
    }

headers = ('First Name', 'Last Name')
data = [['Fred', 'Roberts'], ['George', 'Smith']]

data, headers = style_output(data, headers, style=YourStyle)
Parameters:
  • data (iterable) – An iterable (e.g. list) of rows.
  • headers (iterable) – The column headers.
  • style (str/pygments.style.Style) – A Pygments style. You can create your own styles.
  • header_token (str) – The token type to be used for the headers.
  • odd_row_token (str) – The token type to be used for odd rows.
  • even_row_token (str) – The token type to be used for even rows.
Returns:

The styled data and headers.

Return type:

tuple

Config

Read and write an application’s config files.

class cli_helpers.config.Config(app_name, app_author, filename, default=None, validate=False, write_default=False, additional_dirs=())[source]

Config reader/writer class.

Parameters:
  • app_name (str) – The application’s name.
  • app_author (str) – The application author/organization.
  • filename (str) – The config filename to look for (e.g. config).
  • default (dict/str) – The default config values or absolute path to config file.
  • validate (bool) – Whether or not to validate the config file.
  • write_default (bool) – Whether or not to write the default config file to the user config directory if it doesn’t already exist.
  • additional_dirs (tuple) – Additional directories to check for a config file.
additional_files()[source]

Get a list of absolute paths to the additional config files.

all_config_files()[source]

Get a list of absolute paths to all the config files.

data = None

The ConfigObj instance.

read()[source]

Read the default, additional, system, and user config files.

Raises:DefaultConfigValidationError – There was a validation error with the default file.
read_config_file(f)[source]

Read a config file f.

Parameters:f (str) – The path to a file to read.
read_config_files(files)[source]

Read a list of config files.

Parameters:files (iterable) – An iterable (e.g. list) of files to read.
read_default_config()[source]

Read the default config file.

Raises:DefaultConfigValidationError – There was a validation error with the default file.
system_config_files()[source]

Get a list of absolute paths to the system config files.

user_config_file()[source]

Get the absolute path to the user config file.

write(outfile=None, section=None)[source]

Write the current config to a file (defaults to user config).

Parameters:
  • outfile (str) – The path to the file to write to.
  • section (None/str) – The config section to write, or None to write the entire config.
write_default_config(overwrite=False)[source]

Write the default config to the user’s config file.

Parameters:overwrite (bool) – Write over an existing config if it exists.
exception cli_helpers.config.ConfigError[source]

Base class for exceptions in this module.

exception cli_helpers.config.DefaultConfigValidationError[source]

Indicates the default config file did not validate correctly.

cli_helpers.config.get_system_config_dirs(app_name, app_author, force_xdg=True)[source]

Returns a list of system-wide config folders for the application.

For an example application called "My App" by "Acme", something like the following folders could be returned:

macOS (non-XDG):
['/Library/Application Support/My App']
Mac OS X (XDG):
['/etc/xdg/my-app']
Unix:
['/etc/xdg/my-app']
Windows 7:
['C:\ProgramData\Acme\My App']
Parameters:
  • app_name – the application name. This should be properly capitalized and can contain whitespace.
  • app_author – The app author’s name (or company). This should be properly capitalized and can contain whitespace.
  • force_xdg – if this is set to True, then on macOS the XDG Base Directory Specification will be followed. Has no effect on non-macOS systems.
cli_helpers.config.get_user_config_dir(app_name, app_author, roaming=True, force_xdg=True)[source]

Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.

For an example application called "My App" by "Acme", something like the following folders could be returned:

macOS (non-XDG):
~/Library/Application Support/My App
Mac OS X (XDG):
~/.config/my-app
Unix:
~/.config/my-app
Windows 7 (roaming):
C:\Users\<user>\AppData\Roaming\Acme\My App
Windows 7 (not roaming):
C:\Users\<user>\AppData\Local\Acme\My App
Parameters:
  • app_name – the application name. This should be properly capitalized and can contain whitespace.
  • app_author – The app author’s name (or company). This should be properly capitalized and can contain whitespace.
  • roaming – controls if the folder should be roaming or not on Windows. Has no effect on non-Windows systems.
  • force_xdg – if this is set to True, then on macOS the XDG Base Directory Specification will be followed. Has no effect on non-macOS systems.