Skip to content

Commit 3709be4

Browse files
committed
Added a basic example for dynamically adding do_* commands in a loop
1 parent 693ec59 commit 3709be4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

examples/dynamic_commands.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python3
2+
# coding=utf-8
3+
"""A simple example demonstrating how do_* commands can be created in a loop.
4+
"""
5+
import functools
6+
import cmd2
7+
COMMAND_LIST = ['foo', 'bar', 'baz']
8+
9+
10+
class CommandsInLoop(cmd2.Cmd):
11+
"""Example of dynamically adding do_* commands."""
12+
def __init__(self):
13+
super().__init__(use_ipython=True)
14+
15+
def send_text(self, args: cmd2.Statement, *, text: str):
16+
"""Simulate sending text to a server and printing the response."""
17+
self.poutput(text.capitalize())
18+
19+
def text_help(self, *, text: str):
20+
"""Deal with printing help for the dynamically added commands."""
21+
self.poutput("Simulate sending {!r} to a server and printing the response".format(text))
22+
23+
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+
if __name__ == '__main__':
30+
app = CommandsInLoop()
31+
app.cmdloop()

0 commit comments

Comments
 (0)