shell module

Base classes for implementing CLI utilities and daemons.

ControlShell and DaemonControlShell serve as Python context managers for common resources such as message buffers and process executors. They also handle command line arguments and output to stdout, stderr and/or log files.

Classes

class ctlbase.shell.ControlShell(parser, commandExecutor=None, envConfigName=True, msgBuffer=None, lng=None)

A context manager for creating CLI utilities. Creates and lifecyle-manages the resources typically needed by a control.

__exit__(errorType, error, traceback)

When the context manager exits, the following steps are taken:

  • If the context manager exits due to an exception of type ErrorMessage or ValueError, the corresponding error message is added to the message buffer.

  • Any other exception bubbles up, i.e. is not handled gracefully.

  • An auto-created process executor is auto-closed.

  • The close function or coroutine function of the control set via setControl() is called if it exists.

  • The close function or coroutine function of this context manager is called if it exists. Useful for extensions of ControlShell that control resources of their own.

  • Messages in the message buffer are printed to stdout and stderr as follows:

    • If the -j | --json command line flag is given, all messages in the message buffer are printed to stdout in JSON format. All remaining flags for output handling are ignored at this point. If the -j | --json command line flag is not given, plain text messages are printed to stdout unless the severity is WARNING or ERROR. Then they are printed to stderr.

    • The language of plain text messages is determined by lng.

    • If the -v | --verbose command line flag is given, messages with severity VERBOSE and DEBUG are included in plain text output.

    • Plain text messages are colored according to their severities, unless isColoringDefault is False. Coloring is also suppressed if the COLOR_PRINT environment variable is false.

    • Any plain text string set in printOnExit() is printed to stdout.

  • An auto-created message buffer is auto-closed.

  • The context manager’s asyncio event loop is closed.

If an exit code was set with setExitCode(), it is used as the exit code of the Python process. Otherwise the exit code is determined via the message buffer’s getExitCode() method.

__init__(parser, commandExecutor=None, envConfigName=True, msgBuffer=None, lng=None)

Creates a new control shell with the resources specified in the parameters. Independently of the parameters, always creates a new asyncio event loop for the current thread.

Parameters:
  • parser (argparse.ArgumentParser | argparse.Namespace) – The parser or already parsed namespace with the command line arguments to evaluate.

  • commandExecutor (CommandExecutor | True | None) – A command executor or True for auto-creation. None if no command executor is needed.

  • envConfigName (tuple[str, dict] | str | bool | None) –

    An environment configuration in one of the following forms:

    • As a configuration file name. It may may include a relative or absolute path. See find() for the discovery algorithm.

    • As True to auto-discover a configuration file based on the caller’s normalized module name as returned by getName(). See findConfig() for the discovery algorithm.

    • As None if the control shell does not need an environment configuration.

  • msgBuffer (MessageBuffer | True | None) – The message buffer to which all occurring messages are appended. True for auto-creation. If None, no messages are printed to stdout and stderr.

  • lng (str | True) – A two-letter language code for the messages to be printed to stdout and stderr. If None, the defaults of the translation module are in effect.

static addStandardArgs(parser, isAddAction=True)

Amends an argument parser with arguments common to CLI utilities.

To create a control shell that handles these arguments automatically, simply pass the amended parser to __init__().

It is recommended to add custom arguments before amending the parser with standard arguments.

  • -j | --json flag: Print JSON output to stdout. Handled by __exit__()

  • -v | --verbose flag: Print more verbose messages to stdout. Handled by __exit__().

  • -o | --oknodo flag: Suppress an error if the requested action’s target state is already reached. Passed to performAction() as isOkNodo .

  • --force flag: Force the action even if the target state is already reached. Passed to performAction() as isForced.

  • --noprompt flag: Do not prompt the user for any input, e.g. confirmations or passwords. Its inversion is passed to performAction() as mayPrompt.

  • action (positional argument): The action to perform. An action argument is only added if not yet present in the parser and if isAddAction is set to True.

Parameters:
printOnExit(text)

Sets an additional text to be printed to stdout when this context manager exits.

If a text is set already, the given text is appended with a newline character.

Parameters:

text (str) – The verbatim text to print to stdout.

requestCleanup(signalNumber=None, stackFrame=None)

A Python signal handler injecting a CleaningUp exception into all running code in the current Python process.

The signature is defined in signal.signal().

setControl(control: Control)

Associates the given control with this context manager.

The effects are as follows:

  • The context manager’s message buffer is propagated to the control. If the context manager does not have a message buffer, the opposite takes place: The control’s message buffer is propagated to the context manager.

  • If the context manager’s message buffer does not yet have a default namespace, the namespace of the control is set as its default namespace.

  • When the context manager exits, the close function or coroutine function of the control is called if one exists.

setExitCode(exitCode)

Sets a numeric code to use as exit code when this context manager exits.

Parameters:

exitCode (int) – The exit code to set.

Raises:

ValueError – If the exit code is not between 0 and 255.

commandExecutor

The process executor lifecycle-managed by this context manager.

envConfigDict

The dict holding the parsed environment configuration.

envConfigName

The absolute path of the environment configuration file parsed into envConfigDict.

msgBuffer

The message buffer used by this context manager to print output to stdout and stderr.

class ctlbase.shell.DaemonControlShell(parser, taskMonitor=None, commandExecutor=None, envConfigName=None, msgBuffer=None, lng=None, **kwargs)

A context manager for creating daemons, i.e. long-running processes that monitor system resources and / or provide a service endpoint.

It adds the following features to ControlShell:

  • Auto-creation and lifecycle management for a task monitor. It can be used to schedule tasks in the background, i.e. in the context manager’s asyncio event loop.

  • Support for command line arguments common to daemons.

__exit__(errorType, error, traceback)

When the context manager exits, the following steps are taken in addition to ControlShell:

  • An auto-created task monitor is auto-closed.

__init__(parser, taskMonitor=None, commandExecutor=None, envConfigName=None, msgBuffer=None, lng=None, **kwargs)

Arguments with the same name have the same meaning as with __init__().

Parameters:

taskMonitor (TaskMonitor | True | None) – A task monitor or True for auto-creation. None if no task monitor is needed.

static addStandardArgs(parser)

Amends an argument parser with arguments common to daemons.

To create a control shell that handles these arguments automatically, simply pass the amended parser to __init__().

It is recommended to add custom arguments before amending the parser with standard arguments.

  • --delay: Delay in milliseconds after which the systemd is notified ready. Handled by notifyReady().

  • -e | --errors: Maximum number of errors after which the daemon exits. To be handled by subclasses of DaemonControlShell.

  • -l | --log: Path to the daemon’s log file. Handled by __enter__().

  • --tswidth: The width of the first column in the log output, as number of characters. Handled by __enter__().

  • --print flag: Print messages to stdout in addition to the log file. Handled by __enter__().

Parameters:

parser (argparse.ArgumentParser) – The argument parser to amend.

async notifyReady()

Sends a systemd ready notification.

Useful if the daemon is wrapped into a systemd service unit.

taskMonitor

The task manager lifecycle-managed by this context manager.