44A simple example demonstrating how to integrate tab completion with argparse-based commands.
55"""
66import argparse
7- from typing import List
7+ from typing import Dict , List
88
99from cmd2 import Cmd , Cmd2ArgumentParser , with_argparser , CompletionError , CompletionItem
1010from cmd2 .utils import basic_complete
@@ -30,14 +30,31 @@ def completer_function(text: str, line: str, begidx: int, endidx: int) -> List[s
3030
3131def choices_completion_item () -> List [CompletionItem ]:
3232 """Return CompletionItem instead of strings. These give more context to what's being tab completed."""
33- items = {
34- 1 : "My item" ,
35- 2 : "Another item" ,
36- 3 : "Yet another item"
37- }
33+ items = \
34+ {
35+ 1 : "My item" ,
36+ 2 : "Another item" ,
37+ 3 : "Yet another item"
38+ }
3839 return [CompletionItem (item_id , description ) for item_id , description in items .items ()]
3940
4041
42+ def choices_arg_tokens (arg_tokens : Dict [str , List [str ]]) -> List [str ]:
43+ """
44+ If a choices or completer function/method takes a value called arg_tokens, then it will be
45+ passed a dictionary that maps the command line tokens up through the one being completed
46+ to their argparse argument name. All values of the arg_tokens dictionary are lists, even if
47+ a particular argument expects only 1 token.
48+ """
49+ # Check if choices_function flag has appeared
50+ values = ['choices_function' , 'flag' ]
51+ if 'choices_function' in arg_tokens :
52+ values .append ('is {}' .format (arg_tokens ['choices_function' ][0 ]))
53+ else :
54+ values .append ('not supplied' )
55+ return values
56+
57+
4158class ArgparseCompletion (Cmd ):
4259 def __init__ (self , * args , ** kwargs ):
4360 super ().__init__ (* args , ** kwargs )
@@ -57,34 +74,45 @@ def choices_completion_error(self) -> List[str]:
5774 """
5875 if self .debug :
5976 return self .sport_item_strs
60- raise CompletionError ("Debug must be true" )
77+ raise CompletionError ("debug must be true" )
6178
62- # Parser for complete command
63- complete_parser = Cmd2ArgumentParser (description = "Command demonstrating tab completion with argparse\n "
64- "Notice even the flags of this command tab complete" )
79+ # Parser for example command
80+ example_parser = Cmd2ArgumentParser (description = "Command demonstrating tab completion with argparse\n "
81+ "Notice even the flags of this command tab complete" )
6582
6683 # Tab complete from a list using argparse choices. Set metavar if you don't
6784 # want the entire choices list showing in the usage text for this command.
68- complete_parser .add_argument ('--choices' , choices = food_item_strs , metavar = "CHOICE" )
85+ example_parser .add_argument ('--choices' , choices = food_item_strs , metavar = "CHOICE" ,
86+ help = "tab complete using choices" )
6987
7088 # Tab complete from choices provided by a choices function and choices method
71- complete_parser .add_argument ('--choices_function' , choices_function = choices_function )
72- complete_parser .add_argument ('--choices_method' , choices_method = choices_method )
89+ example_parser .add_argument ('--choices_function' , choices_function = choices_function ,
90+ help = "tab complete using a choices_function" )
91+ example_parser .add_argument ('--choices_method' , choices_method = choices_method ,
92+ help = "tab complete using a choices_method" )
7393
7494 # Tab complete using a completer function and completer method
75- complete_parser .add_argument ('--completer_function' , completer_function = completer_function )
76- complete_parser .add_argument ('--completer_method' , completer_method = Cmd .path_complete )
95+ example_parser .add_argument ('--completer_function' , completer_function = completer_function ,
96+ help = "tab complete using a completer_function" )
97+ example_parser .add_argument ('--completer_method' , completer_method = Cmd .path_complete ,
98+ help = "tab complete using a completer_method" )
7799
78100 # Demonstrate raising a CompletionError while tab completing
79- complete_parser .add_argument ('--completion_error' , choices_method = choices_completion_error )
101+ example_parser .add_argument ('--completion_error' , choices_method = choices_completion_error ,
102+ help = "raise a CompletionError while tab completing if debug is False" )
80103
81104 # Demonstrate returning CompletionItems instead of strings
82- complete_parser .add_argument ('--completion_item' , choices_function = choices_completion_item , metavar = "ITEM_ID" ,
83- descriptive_header = "Description" )
105+ example_parser .add_argument ('--completion_item' , choices_function = choices_completion_item , metavar = "ITEM_ID" ,
106+ descriptive_header = "Description" ,
107+ help = "demonstrate use of CompletionItems" )
108+
109+ # Demonstrate use of arg_tokens dictionary
110+ example_parser .add_argument ('--arg_tokens' , choices_function = choices_arg_tokens ,
111+ help = "demonstrate use of arg_tokens dictionary" )
84112
85- @with_argparser (complete_parser )
86- def do_complete (self , _ : argparse .Namespace ) -> None :
87- """The complete command"""
113+ @with_argparser (example_parser )
114+ def do_example (self , _ : argparse .Namespace ) -> None :
115+ """The example command"""
88116 self .poutput ("I do nothing" )
89117
90118
0 commit comments