summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2020-02-13 15:28:45 -0500
committerKevin Van Brunt <kmvanbrunt@gmail.com>2020-02-13 15:28:45 -0500
commit8cfc02d4fe7f33549ce190aec30535800651e705 (patch)
tree698a98c0bfc39b33cfb4d03db4a887aaa7131d85
parentee93add8d49210da554958e70006db52dde88d1e (diff)
downloadcmd2-git-8cfc02d4fe7f33549ce190aec30535800651e705.tar.gz
Finished argparse completion example
-rw-r--r--examples/argparse_completion.py70
1 files changed, 49 insertions, 21 deletions
diff --git a/examples/argparse_completion.py b/examples/argparse_completion.py
index a089f285..90975d3f 100644
--- a/examples/argparse_completion.py
+++ b/examples/argparse_completion.py
@@ -4,7 +4,7 @@
A simple example demonstrating how to integrate tab completion with argparse-based commands.
"""
import argparse
-from typing import List
+from typing import Dict, List
from cmd2 import Cmd, Cmd2ArgumentParser, with_argparser, CompletionError, CompletionItem
from cmd2.utils import basic_complete
@@ -30,14 +30,31 @@ def completer_function(text: str, line: str, begidx: int, endidx: int) -> List[s
def choices_completion_item() -> List[CompletionItem]:
"""Return CompletionItem instead of strings. These give more context to what's being tab completed."""
- items = {
- 1: "My item",
- 2: "Another item",
- 3: "Yet another item"
- }
+ items = \
+ {
+ 1: "My item",
+ 2: "Another item",
+ 3: "Yet another item"
+ }
return [CompletionItem(item_id, description) for item_id, description in items.items()]
+def choices_arg_tokens(arg_tokens: Dict[str, List[str]]) -> List[str]:
+ """
+ If a choices or completer function/method takes a value called arg_tokens, then it will be
+ passed a dictionary that maps the command line tokens up through the one being completed
+ to their argparse argument name. All values of the arg_tokens dictionary are lists, even if
+ a particular argument expects only 1 token.
+ """
+ # Check if choices_function flag has appeared
+ values = ['choices_function', 'flag']
+ if 'choices_function' in arg_tokens:
+ values.append('is {}'.format(arg_tokens['choices_function'][0]))
+ else:
+ values.append('not supplied')
+ return values
+
+
class ArgparseCompletion(Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -57,34 +74,45 @@ class ArgparseCompletion(Cmd):
"""
if self.debug:
return self.sport_item_strs
- raise CompletionError("Debug must be true")
+ raise CompletionError("debug must be true")
- # Parser for complete command
- complete_parser = Cmd2ArgumentParser(description="Command demonstrating tab completion with argparse\n"
- "Notice even the flags of this command tab complete")
+ # Parser for example command
+ example_parser = Cmd2ArgumentParser(description="Command demonstrating tab completion with argparse\n"
+ "Notice even the flags of this command tab complete")
# Tab complete from a list using argparse choices. Set metavar if you don't
# want the entire choices list showing in the usage text for this command.
- complete_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE")
+ example_parser.add_argument('--choices', choices=food_item_strs, metavar="CHOICE",
+ help="tab complete using choices")
# Tab complete from choices provided by a choices function and choices method
- complete_parser.add_argument('--choices_function', choices_function=choices_function)
- complete_parser.add_argument('--choices_method', choices_method=choices_method)
+ example_parser.add_argument('--choices_function', choices_function=choices_function,
+ help="tab complete using a choices_function")
+ example_parser.add_argument('--choices_method', choices_method=choices_method,
+ help="tab complete using a choices_method")
# Tab complete using a completer function and completer method
- complete_parser.add_argument('--completer_function', completer_function=completer_function)
- complete_parser.add_argument('--completer_method', completer_method=Cmd.path_complete)
+ example_parser.add_argument('--completer_function', completer_function=completer_function,
+ help="tab complete using a completer_function")
+ example_parser.add_argument('--completer_method', completer_method=Cmd.path_complete,
+ help="tab complete using a completer_method")
# Demonstrate raising a CompletionError while tab completing
- complete_parser.add_argument('--completion_error', choices_method=choices_completion_error)
+ example_parser.add_argument('--completion_error', choices_method=choices_completion_error,
+ help="raise a CompletionError while tab completing if debug is False")
# Demonstrate returning CompletionItems instead of strings
- complete_parser.add_argument('--completion_item', choices_function=choices_completion_item, metavar="ITEM_ID",
- descriptive_header="Description")
+ example_parser.add_argument('--completion_item', choices_function=choices_completion_item, metavar="ITEM_ID",
+ descriptive_header="Description",
+ help="demonstrate use of CompletionItems")
+
+ # Demonstrate use of arg_tokens dictionary
+ example_parser.add_argument('--arg_tokens', choices_function=choices_arg_tokens,
+ help="demonstrate use of arg_tokens dictionary")
- @with_argparser(complete_parser)
- def do_complete(self, _: argparse.Namespace) -> None:
- """The complete command"""
+ @with_argparser(example_parser)
+ def do_example(self, _: argparse.Namespace) -> None:
+ """The example command"""
self.poutput("I do nothing")