diff options
author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-01-06 11:52:27 -0500 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-01-06 11:52:27 -0500 |
commit | 6b6809a394b1e0baffad46d7b91f61d77ece128d (patch) | |
tree | a66a69e4fe3f01770f39a0fee60b1b434595decf /examples/dynamic_commands.py | |
parent | c2ce4b0210531a4cec35b14c51395a91ff092b91 (diff) | |
download | cmd2-git-6b6809a394b1e0baffad46d7b91f61d77ece128d.tar.gz |
Updated dynamic commands example to add help category
Diffstat (limited to 'examples/dynamic_commands.py')
-rwxr-xr-x | examples/dynamic_commands.py | 26 |
1 files changed, 20 insertions, 6 deletions
diff --git a/examples/dynamic_commands.py b/examples/dynamic_commands.py index 69816d40..620acb7f 100755 --- a/examples/dynamic_commands.py +++ b/examples/dynamic_commands.py @@ -3,13 +3,32 @@ """A simple example demonstrating how do_* commands can be created in a loop. """ import functools + import cmd2 -COMMAND_LIST = ['foo', 'bar', 'baz'] +from cmd2.constants import COMMAND_FUNC_PREFIX, HELP_FUNC_PREFIX + +COMMAND_LIST = ['foo', 'bar'] +CATEGORY = 'Dynamic Commands' class CommandsInLoop(cmd2.Cmd): """Example of dynamically adding do_* commands.""" def __init__(self): + # Add dynamic commands before calling cmd2.Cmd's init since it validates command names + for command in COMMAND_LIST: + # Create command function and add help category to it + cmd_func = functools.partial(self.send_text, text=command) + cmd2.categorize(cmd_func, CATEGORY) + + # Add command function to CLI object + cmd_func_name = COMMAND_FUNC_PREFIX + command + setattr(self, cmd_func_name, cmd_func) + + # Add help function to CLI object + help_func = functools.partial(self.text_help, text=command) + help_func_name = HELP_FUNC_PREFIX + command + setattr(self, help_func_name, help_func) + super().__init__(use_ipython=True) def send_text(self, args: cmd2.Statement, *, text: str): @@ -21,11 +40,6 @@ class CommandsInLoop(cmd2.Cmd): self.poutput("Simulate sending {!r} to a server and printing the response".format(text)) -for command in COMMAND_LIST: - setattr(CommandsInLoop, 'do_{}'.format(command), functools.partialmethod(CommandsInLoop.send_text, text=command)) - setattr(CommandsInLoop, 'help_{}'.format(command), functools.partialmethod(CommandsInLoop.text_help, text=command)) - - if __name__ == '__main__': app = CommandsInLoop() app.cmdloop() |