cmd2.argparse_custom¶
This module adds capabilities to argparse by patching a few of its functions. It also defines a parser class called Cmd2ArgumentParser which improves error and help output over normal argparse. All cmd2 code uses this parser and it is recommended that developers of cmd2-based apps either use it or write their own parser that inherits from it. This will give a consistent look-and-feel between the help/error output of built-in cmd2 commands and the app-specific commands. If you wish to override the parser used by cmd2’s built-in commands, see override_parser.py example.
Since the new capabilities are added by patching at the argparse API level, they are available whether or not Cmd2ArgumentParser is used. However, the help and error output of Cmd2ArgumentParser is customized to notate nargs ranges whereas any other parser class won’t be as explicit in their output.
Added capabilities
Extends argparse nargs functionality by allowing tuples which specify a range (min, max). To specify a max value with no upper bound, use a 1-item tuple (min,)
Example:
# -f argument expects at least 3 values
parser.add_argument('-f', nargs=(3,))
# -f argument expects 3 to 5 values
parser.add_argument('-f', nargs=(3, 5))
Tab Completion
cmd2 uses its ArgparseCompleter class to enable argparse-based tab completion on all commands that use the @with_argparse wrappers. Out of the box you get tab completion of commands, subcommands, and flag names, as well as instructive hints about the current argument that print when tab is pressed. In addition, you can add tab completion for each argument’s values using parameters passed to add_argument().
Below are the 3 add_argument() parameters for enabling tab completion of an argument’s value. Only one can be used at a time.
choices
- pass a list of values to the choices parameter.
Example:
my_list = ['An Option', 'SomeOtherOption'] parser.add_argument('-o', '--options', choices=my_list)
choices_provider
- pass a function that returns choices. This is good in
cases where the choice list is dynamically generated when the user hits tab.
Example:
def my_choices_provider(self): ... return my_generated_list parser.add_argument("arg", choices_provider=my_choices_provider)
completer
- pass a tab completion function that does custom completion.
cmd2 provides a few completer methods for convenience (e.g., path_complete, delimiter_complete)
Example:
# This adds file-path completion to an argument parser.add_argument('-o', '--options', completer=cmd2.Cmd.path_complete)You can use functools.partial() to prepopulate values of the underlying choices and completer functions/methods.
Example:
# This says to call path_complete with a preset value for its path_filter argument dir_completer = functools.partial(path_complete, path_filter=lambda path: os.path.isdir(path)) parser.add_argument('-o', '--options', completer=dir_completer)
For choices_provider
and completer
, do not set them to a bound method. This
is because ArgparseCompleter passes the self argument explicitly to these
functions. When ArgparseCompleter calls one, it will detect whether it is bound
to a Cmd subclass or CommandSet. If bound to a cmd2.Cmd subclass, it will
pass the app instance as the self argument. If bound to a cmd2.CommandSet
subclass, it will pass the CommandSet instance as the self argument.
Therefore instead of passing something like self.path_complete, pass
cmd2.Cmd.path_complete.
choices_provider
and completer
functions can also be implemented as
standalone functions (i.e. not a member of a class). In this case,
ArgparseCompleter will pass its cmd2.Cmd
app instance as the first
positional argument.
Of the 3 tab completion parameters, choices
is the only one where argparse
validates user input against items in the choices list. This is because the
other 2 parameters are meant to tab complete data sets that are viewed as
dynamic. Therefore it is up to the developer to validate if the user has typed
an acceptable value for these arguments.
There are times when what’s being tab completed is determined by a previous argument on the command line. In theses cases, ArgparseCompleter can pass a dictionary that maps the command line tokens up through the one being completed to their argparse argument name. To receive this dictionary, your choices/completer function should have an argument called arg_tokens.
Example:
def my_choices_provider(self, arg_tokens) def my_completer(self, text, line, begidx, endidx, arg_tokens)
All values of the arg_tokens dictionary are lists, even if a particular argument expects only 1 token. Since ArgparseCompleter is for tab completion, it does not convert the tokens to their actual argument types or validate their values. All tokens are stored in the dictionary as the raw strings provided on the command line. It is up to the developer to determine if the user entered the correct argument type (e.g. int) and validate their values.
CompletionItem Class - This class was added to help in cases where uninformative data is being tab completed. For instance, tab completing ID numbers isn’t very helpful to a user without context. Returning a list of CompletionItems instead of a regular string for completion results will signal the ArgparseCompleter to output the completion results in a table of completion tokens with descriptions instead of just a table of tokens:
Instead of this:
1 2 3
The user sees this:
ITEM_ID Item Name
============================
1 My item
2 Another item
3 Yet another item
The left-most column is the actual value being tab completed and its header is that value’s name. The right column header is defined using the descriptive_header parameter of add_argument(). The right column values come from the CompletionItem.description value.
Example:
token = 1
token_description = "My Item"
completion_item = CompletionItem(token, token_description)
Since descriptive_header and CompletionItem.description are just strings, you can format them in such a way to have multiple columns:
ITEM_ID Item Name Checked Out Due Date
==========================================================
1 My item True 02/02/2022
2 Another item False
3 Yet another item False
To use CompletionItems, just return them from your choices_provider or completer functions. They can also be used as argparse choices. When a CompletionItem is created, it stores the original value (e.g. ID number) and makes it accessible through a property called orig_value. cmd2 has patched argparse so that when evaluating choices, input is compared to CompletionItem.orig_value instead of the CompletionItem instance.
To avoid printing a ton of information to the screen at once when a user presses tab, there is a maximum threshold for the number of CompletionItems that will be shown. Its value is defined in cmd2.Cmd.max_completion_items. It defaults to 50, but can be changed. If the number of completion suggestions exceeds this number, they will be displayed in the typical columnized format and will not include the description value of the CompletionItems.
Patched argparse functions
argparse._ActionsContainer.add_argument
- adds arguments related to tab
completion and enables nargs range parsing. See _add_argument_wrapper for
more details on these arguments.
argparse.ArgumentParser._check_value
- adds support for using
CompletionItems
as argparse choices. When evaluating choices, input is
compared to CompletionItem.orig_value
instead of the CompletionItem
instance.
See _ArgumentParser_check_value for more details.
argparse.ArgumentParser._get_nargs_pattern
- adds support for nargs ranges.
See _get_nargs_pattern_wrapper for more details.
argparse.ArgumentParser._match_argument
- adds support for nargs ranges.
See _match_argument_wrapper for more details.
argparse._SubParsersAction.remove_parser
- new function which removes a
sub-parser from a sub-parsers group. See _SubParsersAction_remove_parser for
more details.
Added accessor methods
cmd2 has patched argparse.Action
to include the following accessor methods
for cases in which you need to manually access the cmd2-specific attributes.
argparse.Action.get_choices_callable()
- See_action_get_choices_callable()
for more details.argparse.Action.set_choices_provider()
- See_action_set_choices_provider()
for more details.argparse.Action.set_completer()
- See_action_set_completer()
for more details.argparse.Action.get_descriptive_header()
- See_action_get_descriptive_header()
for more details.argparse.Action.set_descriptive_header()
- See_action_set_descriptive_header()
for more details.argparse.Action.get_nargs_range()
- See_action_get_nargs_range()
for more details.argparse.Action.set_nargs_range()
- See_action_set_nargs_range()
for more details.argparse.Action.get_suppress_tab_hint()
- See_action_get_suppress_tab_hint()
for more details.argparse.Action.set_suppress_tab_hint()
- See_action_set_suppress_tab_hint()
for more details.
cmd2 has patched argparse.ArgumentParser
to include the following accessor methods
argparse.ArgumentParser.get_ap_completer_type()
- See_ArgumentParser_get_ap_completer_type()
for more details.argparse.Action.set_ap_completer_type()
- See_ArgumentParser_set_ap_completer_type()
for more details.
Subcommand removal
cmd2 has patched argparse._SubParsersAction
to include a remove_parser()
method which can be used to remove a subcommand.
argparse._SubParsersAction.remove_parser
- new function which removes a
sub-parser from a sub-parsers group. See
_SubParsersAction_remove_parser()
for more details.
-
class
cmd2.argparse_custom.
ChoicesCallable
(is_completer: bool, to_call: Union[cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens, cmd2.argparse_custom.ChoicesProviderFuncBase, cmd2.argparse_custom.ChoicesProviderFuncWithTokens])¶ Enables using a callable as the choices provider for an argparse argument. While argparse has the built-in choices attribute, it is limited to an iterable.
-
class
cmd2.argparse_custom.
ChoicesProviderFuncBase
(*args, **kwargs)¶ Function that returns a list of choices in support of tab completion
-
class
cmd2.argparse_custom.
ChoicesProviderFuncWithTokens
(*args, **kwargs)¶ Function that returns a list of choices in support of tab completion and accepts a dictionary of prior arguments.
-
class
cmd2.argparse_custom.
Cmd2ArgumentParser
(prog: Optional[str] = None, usage: Optional[str] = None, description: Optional[str] = None, epilog: Optional[str] = None, parents: Sequence[argparse.ArgumentParser] = (), formatter_class: Type[argparse.HelpFormatter] = <class 'cmd2.argparse_custom.Cmd2HelpFormatter'>, prefix_chars: str = '-', fromfile_prefix_chars: Optional[str] = None, argument_default: Optional[str] = None, conflict_handler: str = 'error', add_help: bool = True, allow_abbrev: bool = True, *, ap_completer_type: Optional[Type[ArgparseCompleter]] = None)¶ Custom ArgumentParser class that improves error and help output
-
add_subparsers
(**kwargs) → argparse._SubParsersAction¶ Custom override. Sets a default title if one was not given.
Parameters: kwargs – additional keyword arguments Returns: argparse Subparser Action
-
error
(message: str) → NoReturn¶ Custom override that applies custom formatting to the error message
-
format_help
() → str¶ Copy of format_help() from argparse.ArgumentParser with tweaks to separately display required parameters
-
-
class
cmd2.argparse_custom.
Cmd2AttributeWrapper
(attribute: Any)¶ Wraps a cmd2-specific attribute added to an argparse Namespace. This makes it easy to know which attributes in a Namespace are arguments from a parser and which were added by cmd2.
-
get
() → Any¶ Get the value of the attribute
-
set
(new_val: Any) → None¶ Set the value of the attribute
-
-
class
cmd2.argparse_custom.
Cmd2HelpFormatter
(prog, indent_increment=2, max_help_position=24, width=None)¶ Custom help formatter to configure ordering of help text
-
class
cmd2.argparse_custom.
CompleterFuncBase
(*args, **kwargs)¶ Function to support tab completion with the provided state of the user prompt
-
class
cmd2.argparse_custom.
CompleterFuncWithTokens
(*args, **kwargs)¶ Function to support tab completion with the provided state of the user prompt and accepts a dictionary of prior arguments.
-
class
cmd2.argparse_custom.
CompletionItem
(value: object, description: str = '', *args)¶ Completion item with descriptive text attached
See header of this file for more information
-
orig_value
¶ Read-only property for _orig_value
-
-
cmd2.argparse_custom.
DEFAULT_ARGUMENT_PARSER
¶
-
cmd2.argparse_custom.
generate_range_error
(range_min: int, range_max: Union[int, float]) → str¶ Generate an error message when the the number of arguments provided is not within the expected range
-
cmd2.argparse_custom.
register_argparse_argument_parameter
(param_name: str, param_type: Optional[Type[Any]]) → None¶ Registers a custom argparse argument parameter.
The registered name will then be a recognized keyword parameter to the parser’s add_argument() function.
An accessor functions will be added to the parameter’s Action object in the form of:
get_{param_name}()
andset_{param_name}(value)
.Parameters: - param_name – Name of the parameter to add.
- param_type – Type of the parameter to add.
-
cmd2.argparse_custom.
set_default_argument_parser_type
(parser_type: Type[argparse.ArgumentParser]) → None¶ Set the default ArgumentParser class for a cmd2 app. This must be called prior to loading cmd2.py if you want to override the parser for cmd2’s built-in commands. See examples/override_parser.py.
Added Accessor Methods¶
-
cmd2.argparse_custom.
_action_get_choices_callable
(self: argparse.Action) → Optional[cmd2.argparse_custom.ChoicesCallable]¶ Get the choices_callable attribute of an argparse Action.
This function is added by cmd2 as a method called
get_choices_callable()
toargparse.Action
class.To call:
action.get_choices_callable()
Parameters: self – argparse Action being queried Returns: A ChoicesCallable instance or None if attribute does not exist
-
cmd2.argparse_custom.
_action_set_choices_provider
(self: argparse.Action, choices_provider: Union[cmd2.argparse_custom.ChoicesProviderFuncBase, cmd2.argparse_custom.ChoicesProviderFuncWithTokens]) → None¶ Set choices_provider of an argparse Action.
This function is added by cmd2 as a method called
set_choices_callable()
toargparse.Action
class.To call:
action.set_choices_provider(choices_provider)
Parameters: - self – action being edited
- choices_provider – the choices_provider instance to use
Raises: TypeError if used on incompatible action type
-
cmd2.argparse_custom.
_action_set_completer
(self: argparse.Action, completer: Union[cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens]) → None¶ Set completer of an argparse Action.
This function is added by cmd2 as a method called
set_completer()
toargparse.Action
class.To call:
action.set_completer(completer)
Parameters: - self – action being edited
- completer – the completer instance to use
Raises: TypeError if used on incompatible action type
-
cmd2.argparse_custom.
_action_get_descriptive_header
(self: argparse.Action) → Optional[str]¶ Get the descriptive_header attribute of an argparse Action.
This function is added by cmd2 as a method called
get_descriptive_header()
toargparse.Action
class.To call:
action.get_descriptive_header()
Parameters: self – argparse Action being queried Returns: The value of descriptive_header or None if attribute does not exist
-
cmd2.argparse_custom.
_action_set_descriptive_header
(self: argparse.Action, descriptive_header: Optional[str]) → None¶ Set the descriptive_header attribute of an argparse Action.
This function is added by cmd2 as a method called
set_descriptive_header()
toargparse.Action
class.To call:
action.set_descriptive_header(descriptive_header)
Parameters: - self – argparse Action being updated
- descriptive_header – value being assigned
-
cmd2.argparse_custom.
_action_get_nargs_range
(self: argparse.Action) → Optional[Tuple[int, Union[int, float]]]¶ Get the nargs_range attribute of an argparse Action.
This function is added by cmd2 as a method called
get_nargs_range()
toargparse.Action
class.To call:
action.get_nargs_range()
Parameters: self – argparse Action being queried Returns: The value of nargs_range or None if attribute does not exist
-
cmd2.argparse_custom.
_action_set_nargs_range
(self: argparse.Action, nargs_range: Optional[Tuple[int, Union[int, float]]]) → None¶ Set the nargs_range attribute of an argparse Action.
This function is added by cmd2 as a method called
set_nargs_range()
toargparse.Action
class.To call:
action.set_nargs_range(nargs_range)
Parameters: - self – argparse Action being updated
- nargs_range – value being assigned
-
cmd2.argparse_custom.
_action_get_suppress_tab_hint
(self: argparse.Action) → bool¶ Get the suppress_tab_hint attribute of an argparse Action.
This function is added by cmd2 as a method called
get_suppress_tab_hint()
toargparse.Action
class.To call:
action.get_suppress_tab_hint()
Parameters: self – argparse Action being queried Returns: The value of suppress_tab_hint or False if attribute does not exist
-
cmd2.argparse_custom.
_action_set_suppress_tab_hint
(self: argparse.Action, suppress_tab_hint: bool) → None¶ Set the suppress_tab_hint attribute of an argparse Action.
This function is added by cmd2 as a method called
set_suppress_tab_hint()
toargparse.Action
class.To call:
action.set_suppress_tab_hint(suppress_tab_hint)
Parameters: - self – argparse Action being updated
- suppress_tab_hint – value being assigned
-
cmd2.argparse_custom.
_ArgumentParser_get_ap_completer_type
(self: argparse.ArgumentParser) → Optional[Type[ArgparseCompleter]]¶ Get the ap_completer_type attribute of an argparse ArgumentParser.
This function is added by cmd2 as a method called
get_ap_completer_type()
toargparse.ArgumentParser
class.To call:
parser.get_ap_completer_type()
Parameters: self – ArgumentParser being queried Returns: An ArgparseCompleter-based class or None if attribute does not exist
-
cmd2.argparse_custom.
_ArgumentParser_set_ap_completer_type
(self: argparse.ArgumentParser, ap_completer_type: Type[ArgparseCompleter]) → None¶ Set the ap_completer_type attribute of an argparse ArgumentParser.
This function is added by cmd2 as a method called
set_ap_completer_type()
toargparse.ArgumentParser
class.To call:
parser.set_ap_completer_type(ap_completer_type)
Parameters: - self – ArgumentParser being edited
- ap_completer_type – the custom ArgparseCompleter-based class to use when tab completing arguments for this parser
Subcommand Removal¶
-
cmd2.argparse_custom.
_SubParsersAction_remove_parser
(self: argparse._SubParsersAction, name: str) → None¶ Removes a sub-parser from a sub-parsers group. Used to remove subcommands from a parser.
This function is added by cmd2 as a method called
remove_parser()
toargparse._SubParsersAction
class.To call:
action.remove_parser(name)
Parameters: - self – instance of the _SubParsersAction being edited
- name – name of the subcommand for the sub-parser to remove