summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2019-09-16 11:17:21 -0400
committerGitHub <noreply@github.com>2019-09-16 11:17:21 -0400
commitf10674e6db245da5b4062aef3391d54c33277255 (patch)
treed00e6541e574b49c9c15a063faeb6c13ada47a6e
parent693ec59719edc4384739392a0daea73c922b91c3 (diff)
parent92fb7902b3903d602355d2159dccddbc01b81ee2 (diff)
downloadcmd2-git-f10674e6db245da5b4062aef3391d54c33277255.tar.gz
Merge pull request #775 from python-cmd2/dynamic_commands.py
Added a basic example for dynamically adding do_* commands in a loop
-rw-r--r--CHANGELOG.md1
-rwxr-xr-xcmd2/cmd2.py4
-rwxr-xr-xexamples/dynamic_commands.py31
3 files changed, 36 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24063db3..59cd99fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
* Fixed a bug when running a cmd2 application on Linux without Gtk libraries installed
* Enhancements
* No longer treating empty text scripts as an error condition
+ * Allow dynamically extending a `cmd2.Cmd` object instance with a `do_xxx` method at runtime
## 0.9.16 (August 7, 2019)
* Bug Fixes
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index a0a49a51..610ec897 100755
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1596,6 +1596,10 @@ class Cmd(cmd.Cmd):
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
return completer.complete_command(tokens, text, line, begidx, endidx)
+ def get_names(self):
+ """Return an alphabetized list of names comprising the attributes of the cmd2 class instance."""
+ return dir(self)
+
def get_all_commands(self) -> List[str]:
"""Return a list of all commands"""
return [name[len(COMMAND_FUNC_PREFIX):] for name in self.get_names()
diff --git a/examples/dynamic_commands.py b/examples/dynamic_commands.py
new file mode 100755
index 00000000..69816d40
--- /dev/null
+++ b/examples/dynamic_commands.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+# coding=utf-8
+"""A simple example demonstrating how do_* commands can be created in a loop.
+"""
+import functools
+import cmd2
+COMMAND_LIST = ['foo', 'bar', 'baz']
+
+
+class CommandsInLoop(cmd2.Cmd):
+ """Example of dynamically adding do_* commands."""
+ def __init__(self):
+ super().__init__(use_ipython=True)
+
+ def send_text(self, args: cmd2.Statement, *, text: str):
+ """Simulate sending text to a server and printing the response."""
+ self.poutput(text.capitalize())
+
+ def text_help(self, *, text: str):
+ """Deal with printing help for the dynamically added commands."""
+ 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()