Skip to content

Commit f10674e

Browse files
authored
Merge pull request #775 from python-cmd2/dynamic_commands.py
Added a basic example for dynamically adding do_* commands in a loop
2 parents 693ec59 + 92fb790 commit f10674e

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Fixed a bug when running a cmd2 application on Linux without Gtk libraries installed
55
* Enhancements
66
* No longer treating empty text scripts as an error condition
7+
* Allow dynamically extending a `cmd2.Cmd` object instance with a `do_xxx` method at runtime
78

89
## 0.9.16 (August 7, 2019)
910
* Bug Fixes

cmd2/cmd2.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,6 +1596,10 @@ def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int,
15961596
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
15971597
return completer.complete_command(tokens, text, line, begidx, endidx)
15981598

1599+
def get_names(self):
1600+
"""Return an alphabetized list of names comprising the attributes of the cmd2 class instance."""
1601+
return dir(self)
1602+
15991603
def get_all_commands(self) -> List[str]:
16001604
"""Return a list of all commands"""
16011605
return [name[len(COMMAND_FUNC_PREFIX):] for name in self.get_names()

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)