Runner

class nutcli.runner.Runner(name, parser, logger=None, timeout_exit_code=255)

Bases: object

CLI Commands Runner.

This is the main interface that takes care of processing arguments and executing requested commands.

Example usage
# Create argument parser.
parser = argparse.ArgumentParser()

# Create the runner object.
runner = Runner('my-cli', parser).setup_parser()

# Parse arguments - the runner internally process its own arguments
# that were setup by previous call to `setup_parser()`.
args = runner.parse_args(argv)

# You can handle your own global arguments here.

# Now we setup the default logger - it produces output to stdout
# and stderr.
runner.default_logger()

# And finally, we execute the requested command and store its result
# in `rc`.
rc = runner.execute(args)
Parameters
  • name (str) – Runner name that will be visible in logs.

  • parser (argparse.ArgumentParser) – Application argparse parser.

  • logger (logger, optional) – Logger to be used within the application, defaults to None (= nutcli.message)

  • timeout_exit_code (int, optional) – Return code in case of timeout error, defaults to 255

setup_parser(options=None)

Setup nutcli default options.

The options are:

  • --log-execution: If set, calls decorated with nutcli.decorators.LogExecution will be printed to the logger.

  • --dry-run: If set, calls decorated with nutcli.decorators.SideEffect will not be executed.,

  • --colors, --no-colors: Enable or disable colorized output. If not present, colors are enabled when stdout is a terminal.

  • --log-tag, --no-log-tag: Enable or disable message prefix when logging with default logger.

Note

You can override the option names by providing the options parameter. For example:

options = {
    'log-execution': 'log',
    'dry-run': 'no-side-effects',
    'colors': 'tty',
    'log-tag': 'tag'
}
Parameters

options (dict of str:str, optional) – Override options names, defaults to None

Returns

Self.

Return type

Runner

parse_args(argv)

Parse arguments and process internal nutcli arguments.

Parameters

argv (list of str) – Command line arguments.

Returns

Parsed arguments in namespace.

Return type

argparse.Namespace

default_logger()

Setup default logger handlers.

The DEBUG and INFO levels will be printed to stdout. WARNING, ERROR and CRITICAL are sent to stderr.

All messages are prefixed with [runner-name] string were the name is taken from the constructor.

Returns

Self.

Return type

Runner

execute(args, shell=None)

Process the arguments and either execute the command or print the usage message.

Parameters
  • args (argparse.Namespace) – Parsed arguments in namespace form.

  • shell (Shell, optional) – Shell that will be used by actors, defaults to None (= Shell())

Returns

Actor return code.

Return type

int