| 1 |
|
| 2 |
"""A simple example demonstrating how do_* commands can be created in a loop.""" |
| 3 |
|
| 4 |
import functools |
| 5 |
|
| 6 |
import cmd2 |
| 7 |
from cmd2.constants import ( |
| 8 |
COMMAND_FUNC_PREFIX, |
| 9 |
HELP_FUNC_PREFIX, |
| 10 |
) |
| 11 |
|
| 12 |
COMMAND_LIST = ["foo", "bar"] |
| 13 |
CATEGORY = "Dynamic Commands" |
| 14 |
|
| 15 |
|
| 16 |
class CommandsInLoop(cmd2.Cmd): |
| 17 |
"""Example of dynamically adding do_* commands.""" |
| 18 |
|
| 19 |
def __init__(self) -> None: |
| 20 |
|
| 21 |
for command in COMMAND_LIST: |
| 22 |
|
| 23 |
cmd_func = functools.partial(self.send_text, text=command) |
| 24 |
cmd2.categorize(cmd_func, CATEGORY) |
| 25 |
|
| 26 |
|
| 27 |
cmd_func_name = COMMAND_FUNC_PREFIX + command |
| 28 |
setattr(self, cmd_func_name, cmd_func) |
| 29 |
|
| 30 |
|
| 31 |
help_func = functools.partial(self.text_help, text=command) |
| 32 |
help_func_name = HELP_FUNC_PREFIX + command |
| 33 |
setattr(self, help_func_name, help_func) |
| 34 |
|
| 35 |
super().__init__(include_ipy=True) |
| 36 |
|
| 37 |
def send_text(self, _args: cmd2.Statement, *, text: str) -> None: |
| 38 |
"""Simulate sending text to a server and printing the response.""" |
| 39 |
self.poutput(text.capitalize()) |
| 40 |
|
| 41 |
def text_help(self, *, text: str) -> None: |
| 42 |
"""Deal with printing help for the dynamically added commands.""" |
| 43 |
self.poutput(f"Simulate sending {text!r} to a server and printing the response") |
| 44 |
|
| 45 |
|
| 46 |
if __name__ == "__main__": |
| 47 |
app = CommandsInLoop() |
| 48 |
app.cmdloop() |