3
3
"""A simple example demonstrating how do_* commands can be created in a loop.
4
4
"""
5
5
import functools
6
+
6
7
import cmd2
7
- COMMAND_LIST = ['foo' , 'bar' , 'baz' ]
8
+ from cmd2 .constants import COMMAND_FUNC_PREFIX , HELP_FUNC_PREFIX
9
+
10
+ COMMAND_LIST = ['foo' , 'bar' ]
11
+ CATEGORY = 'Dynamic Commands'
8
12
9
13
10
14
class CommandsInLoop (cmd2 .Cmd ):
11
15
"""Example of dynamically adding do_* commands."""
12
16
def __init__ (self ):
17
+ # Add dynamic commands before calling cmd2.Cmd's init since it validates command names
18
+ for command in COMMAND_LIST :
19
+ # Create command function and add help category to it
20
+ cmd_func = functools .partial (self .send_text , text = command )
21
+ cmd2 .categorize (cmd_func , CATEGORY )
22
+
23
+ # Add command function to CLI object
24
+ cmd_func_name = COMMAND_FUNC_PREFIX + command
25
+ setattr (self , cmd_func_name , cmd_func )
26
+
27
+ # Add help function to CLI object
28
+ help_func = functools .partial (self .text_help , text = command )
29
+ help_func_name = HELP_FUNC_PREFIX + command
30
+ setattr (self , help_func_name , help_func )
31
+
13
32
super ().__init__ (use_ipython = True )
14
33
15
34
def send_text (self , args : cmd2 .Statement , * , text : str ):
@@ -21,11 +40,6 @@ def text_help(self, *, text: str):
21
40
self .poutput ("Simulate sending {!r} to a server and printing the response" .format (text ))
22
41
23
42
24
- for command in COMMAND_LIST :
25
- setattr (CommandsInLoop , 'do_{}' .format (command ), functools .partialmethod (CommandsInLoop .send_text , text = command ))
26
- setattr (CommandsInLoop , 'help_{}' .format (command ), functools .partialmethod (CommandsInLoop .text_help , text = command ))
27
-
28
-
29
43
if __name__ == '__main__' :
30
44
app = CommandsInLoop ()
31
45
app .cmdloop ()
0 commit comments