From 3709be461b1d22ed934218b3ba1c3a335922a156 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Sun, 15 Sep 2019 13:48:25 -0400 Subject: Added a basic example for dynamically adding do_* commands in a loop --- examples/dynamic_commands.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100755 examples/dynamic_commands.py (limited to 'examples/dynamic_commands.py') 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() -- cgit v1.2.1