diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-09-15 13:48:25 -0400 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-09-15 13:48:25 -0400 |
commit | 3709be461b1d22ed934218b3ba1c3a335922a156 (patch) | |
tree | 837cb6724cbef873a46bfa0e421baeef299cfd71 /examples/dynamic_commands.py | |
parent | 693ec59719edc4384739392a0daea73c922b91c3 (diff) | |
download | cmd2-git-3709be461b1d22ed934218b3ba1c3a335922a156.tar.gz |
Added a basic example for dynamically adding do_* commands in a loop
Diffstat (limited to 'examples/dynamic_commands.py')
-rwxr-xr-x | examples/dynamic_commands.py | 31 |
1 files changed, 31 insertions, 0 deletions
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() |