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 configuredErrorHandler
.To be able to store a reference to the (possibly resolved subcommand) command instance, you should instead use the above-mentioned methods separately.
- Parameters:
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:
- Returns:
A Command instance with parsed arguments that is ready for
__call__()
ormain()
- __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 theerror_handler
parameter during Command class initialization. To skip error handling, define the class witherror_handler=None
.Calls the following methods in order:
- _pre_init_actions_(*args, **kwargs)[source]
The first method called by
__call__()
(beforemain()
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 withbefore_main=True
andalways_available=True
in their configured order.- Parameters:
args¶ – Positional arguments to pass to the
action_flag
methodskwargs¶ – 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 beforemain()
is called.Calls all of the specified
before_main()
/action_flag
actions that were defined withbefore_main=True
andalways_available=False
in their configured order.- Parameters:
args¶ – Positional arguments to pass to the
action_flag
methodskwargs¶ – 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 callsuper().main(*args, **kwargs)
.Initialization code that is common for all actions, or that should be run before
_before_main_()
should be placed in__init__
.
- _after_main_(*args, **kwargs)[source]
Called by
__call__()
aftermain()
is called. Calls all of the specifiedafter_main()
/action_flag
actions that were defined withbefore_main=False
in their configured order.- Parameters:
args¶ – Positional arguments to pass to the
action_flag
methodskwargs¶ – Keyword arguments to pass to the
action_flag
methods
- class cli_command_parser.commands.AsyncCommand[source]
-
Asynchronous version of the main class that other Commands should extend.
To run an AsyncCommand, both
main()
andparse_and_run()
can be used as if running a synchronousCommand
. The asynchronous version ofparse_and_run()
handles callingasyncio.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, andAction
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, thenasyncio.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 callasyncio.run()
- it is meant to be used asawait MyCommand.parse_and_await()
with an existing event loop.Simpler applications can likely use the easier
main()
function orparse_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 itsparse_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.