2
2
# coding=utf-8
3
3
"""
4
4
A simple example demonstrating how to enable tab completion by assigning a completer function to do_* commands.
5
- This also demonstrates capabilities of the following completer methods included with cmd2:
6
- - delimiter_completer
7
- - flag_based_complete (see note below)
8
- - index_based_complete (see note below)
5
+ This also demonstrates capabilities of the following completer features included with cmd2:
6
+ - CompletionError exceptions
7
+ - delimiter_completer()
8
+ - flag_based_complete() (see note below)
9
+ - index_based_complete() (see note below)
9
10
10
11
flag_based_complete() and index_based_complete() are basic methods and should only be used if you are not
11
12
familiar with argparse. The recommended approach for tab completing positional tokens and flags is to use
12
13
argparse-based completion. For an example integrating tab completion with argparse, see argparse_completion.py
13
14
"""
14
15
import functools
16
+ from typing import List
15
17
16
18
import cmd2
19
+ from cmd2 import ansi
17
20
18
21
# List of strings used with completion functions
19
22
food_item_strs = ['Pizza' , 'Ham' , 'Ham Sandwich' , 'Potato' ]
@@ -42,7 +45,7 @@ def do_flag_based(self, statement: cmd2.Statement):
42
45
"""
43
46
self .poutput ("Args: {}" .format (statement .args ))
44
47
45
- def complete_flag_based (self , text , line , begidx , endidx ):
48
+ def complete_flag_based (self , text , line , begidx , endidx ) -> List [ str ] :
46
49
"""Completion function for do_flag_based"""
47
50
flag_dict = \
48
51
{
@@ -65,7 +68,7 @@ def do_index_based(self, statement: cmd2.Statement):
65
68
"""Tab completes first 3 arguments using index_based_complete"""
66
69
self .poutput ("Args: {}" .format (statement .args ))
67
70
68
- def complete_index_based (self , text , line , begidx , endidx ):
71
+ def complete_index_based (self , text , line , begidx , endidx ) -> List [ str ] :
69
72
"""Completion function for do_index_based"""
70
73
index_dict = \
71
74
{
@@ -84,6 +87,20 @@ def do_delimiter_complete(self, statement: cmd2.Statement):
84
87
complete_delimiter_complete = functools .partialmethod (cmd2 .Cmd .delimiter_complete ,
85
88
match_against = file_strs , delimiter = '/' )
86
89
90
+ def do_raise_error (self , statement : cmd2 .Statement ):
91
+ """Demonstrates effect of raising CompletionError"""
92
+ self .poutput ("Args: {}" .format (statement .args ))
93
+
94
+ def complete_raise_error (self , text , line , begidx , endidx ) -> List [str ]:
95
+ """
96
+ CompletionErrors can be raised if an error occurs while tab completing.
97
+
98
+ Example use cases
99
+ - Reading a database to retrieve a tab completion data set failed
100
+ - A previous command line argument that determines the data set being completed is invalid
101
+ """
102
+ raise cmd2 .CompletionError (ansi .style_error ("This is how a CompletionError behaves" ))
103
+
87
104
88
105
if __name__ == '__main__' :
89
106
import sys
0 commit comments