Commands Module

The core Command classes that are intended as the entry point for a given program.

author:

Doug Skrypa

class cli_command_parser.commands.Command[source]

Bases: ABC

The main class that other Commands should extend.

ctx: Context

The parsing Context used for this Command. Provided here for convenience - this reference to it is not used by any CLI Command Parser internals, so it is safe for subclasses to redefine / overwrite it.

classmethod parse_and_run(argv: Sequence[str] = None, **kwargs) CommandObj | None[source]
classmethod parse_and_run(argv: Sequence[str] = None, **kwargs) CommandObj | None

Primary entry point for parsing arguments, resolving subcommands, and running a command.

Calls parse() to parse arguments and resolve subcommands, then calls __call__() on the resulting Command instance. Handles exceptions during parsing using the configured ErrorHandler.

To be able to store a reference to the (possibly resolved subcommand) command instance, you should instead use the above-mentioned methods separately.

Parameters:
  • argv – The arguments to parse (defaults to sys.argv)

  • kwargs – Keyword arguments to pass to __call__()

Returns:

The Command instance with parsed arguments for which __call__() was already called.

classmethod parse(argv: Sequence[str] = None) CommandObj[source]
classmethod parse(argv: Sequence[str] = None) CommandObj

Parses the specified arguments (or sys.argv), and resolves the final subcommand class based on the parsed arguments, if necessary. Initializes the Command, but does not call any of its other methods.

Parameters:

argv – The arguments to parse (defaults to sys.argv)

Returns:

A Command instance with parsed arguments that is ready for __call__() or main()

__call__(*args, **kwargs) int[source]

Primary entry point for running a command. Subclasses generally should not override this method.

Handles exceptions using the configured ErrorHandler. Alternate error handlers can be specified via the error_handler parameter during Command class initialization. To skip error handling, define the class with error_handler=None.

Calls the following methods in order:

Parameters:
  • args – Positional arguments to pass to the methods listed above

  • kwargs – Keyword arguments to pass to the methods listed above

Returns:

The total number of actions that were taken

_pre_init_actions_(*args, **kwargs)[source]

The first method called by __call__() (before main() and others).

Validates the number of ActionFlags that were specified, and calls all of the specified before_main() / action_flag actions such as --help that were defined with before_main=True and always_available=True in their configured order.

Parameters:
  • args – Positional arguments to pass to the action_flag methods

  • kwargs – Keyword arguments to pass to the action_flag methods

_init_command_(*args, **kwargs)[source]

Called by __call__() after _pre_init_actions_() and before _before_main_().

Safe to override without calling super()._init_command_() - the base implementation is a placeholder intended to allow subclasses to perform initialization tasks. This method is called after actions like --help have been processed, so more resource-intensive initialization operations or those that may have side effects that should not occur when the application does nothing should be placed here instead of in __init__.

Actions like initializing logging are recommended to be placed in this method.

Parameters:
  • args – Positional arguments that were passed to __call__()

  • kwargs – Keyword arguments that were passed to __call__()

_before_main_(*args, **kwargs)[source]

Called by __call__() after _init_command_() and before main() is called.

Calls all of the specified before_main() / action_flag actions that were defined with before_main=True and always_available=False in their configured order.

Parameters:
  • args – Positional arguments to pass to the action_flag methods

  • kwargs – Keyword arguments to pass to the action_flag methods

main(*args, **kwargs) int | None[source]

Primary method that is called when running a Command.

If any arguments were specified that are associated with triggering a method that was decorated / registered as a positional Action’s target method, then that method is called here.

Commands that do not have any positional Actions can override this method, and do not need to call super().main(*args, **kwargs).

Initialization code that is common for all actions, or that should be run before _before_main_() should be placed in __init__.

Parameters:
  • args – Positional arguments to pass to the action method

  • kwargs – Keyword arguments to pass to the action method

Returns:

The total number of actions that were taken so far

_after_main_(*args, **kwargs)[source]

Called by __call__() after main() is called. Calls all of the specified after_main() / action_flag actions that were defined with before_main=False in their configured order.

Parameters:
  • args – Positional arguments to pass to the action_flag methods

  • kwargs – Keyword arguments to pass to the action_flag methods

class cli_command_parser.commands.AsyncCommand[source]

Bases: Command, ABC

Asynchronous version of the main class that other Commands should extend.

To run an AsyncCommand, both main() and parse_and_run() can be used as if running a synchronous Command. The asynchronous version of parse_and_run() handles calling asyncio.run().

For applications that need more direct control over how the event loop is run, parse_and_await() can be used instead.

All _sunder_ methods supported by Command may be overridden with either synchronous or async versions, and Action target methods may similarly be defined either way as well.

classmethod parse_and_run(argv=None, **kwargs)[source]

Asynchronous version of Command.parse_and_run(). Argument parsing is handled synchronously, then asyncio.run() is called with the parsed command’s __call__() coroutine.

For applications that need more direct control over how the event loop is run, parse_and_await() can be used instead.

async classmethod parse_and_await(argv=None, **kwargs)[source]

Coroutine alternative to parse_and_run(). This method does NOT call asyncio.run() - it is meant to be used as await MyCommand.parse_and_await() with an existing event loop.

Simpler applications can likely use the easier main() function or parse_and_run() instead.

async __call__(*args, **kwargs) int[source]

Asynchronous version of Command.__call__().

async _pre_init_actions_(*args, **kwargs)[source]

Asynchronous version of Command._pre_init_actions_().

async _before_main_(*args, **kwargs)[source]

Asynchronous version of Command._before_main_().

async main(*args, **kwargs) int | None[source]

Asynchronous version of Command.main().

async _after_main_(*args, **kwargs)[source]

Asynchronous version of Command._after_main_().

cli_command_parser.commands.main(argv: Argv = None, return_command: Bool = False, **kwargs) CommandObj | None[source]

Convenience function that can be used as the main entry point for a program.

As long as only one Command subclass is present, this function will detect it and call its parse_and_run() method. Subcommands do not count as direct subclasses of Command, so this function will continue to work even if subcommands are present (as long as they extend their parent command).

If multiple direct subclasses of Command are detected, or if no direct subclasses can be found, then a RuntimeError will be raised. In such cases, you must explicitly call parse_and_run() on the command that is intended to be the primary entry point.

Parameters:
  • argv – The sequence of arguments to parse. Defaults to sys.argv if not specified.

  • return_command – Whether the parsed Command that ran should be returned.

  • kwargs – Keyword arguments to pass through to parse_and_run()

Raises:

RuntimeError if multiple subclasses are detected, or if no subclasses could be found.