Skip to content

Commit 162603e

Browse files
authored
Merge pull request #840 from python-cmd2/categorize_dynamic
Categorize dynamic
2 parents 3fc6388 + 5dac940 commit 162603e

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

examples/dynamic_commands.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,32 @@
33
"""A simple example demonstrating how do_* commands can be created in a loop.
44
"""
55
import functools
6+
67
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'
812

913

1014
class CommandsInLoop(cmd2.Cmd):
1115
"""Example of dynamically adding do_* commands."""
1216
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+
1332
super().__init__(use_ipython=True)
1433

1534
def send_text(self, args: cmd2.Statement, *, text: str):
@@ -21,11 +40,6 @@ def text_help(self, *, text: str):
2140
self.poutput("Simulate sending {!r} to a server and printing the response".format(text))
2241

2342

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-
2943
if __name__ == '__main__':
3044
app = CommandsInLoop()
3145
app.cmdloop()

0 commit comments

Comments
 (0)