I’m writing a python command-line tool using the cmd2 module which is an enhanced version of cmd. The tool is an administration application and is used to administer a number of sub-modules.
I’d like to structure the code so that each sub-module has its own class responsible for providing the commands that can be executed on that module. But I’m not sure how to structure this given how the command class works.
So what I’d like is something like:
import cmd
class ConsoleApp(cmd.Cmd):
# this is the main app and should get the commands from the sub-modules
app = ConsoleApp()
app.cmdloop()
And then the sub-modules would be separately defined.
class SubModuleA():
def do_sm_a_command_1(self, line):
print "sm a command 1"
class SubModuleB():
def do_sm_b_command_1(self, line):
print "sm b command 2"
How can I structure this so that the main app will pick up the commands from the sub-modules?
Thanks, Jon
You may have some luck structuring your SubModules as Plugins to the main ConsoleApp. You’d need a couple of new methods on ConsoleApp. Something like
add_command_module(self, klass)which would just append the klass (SubModuleA for example) to some list inside ConsoleApp.Then in ConsoleApp, override the
onecmdmethod to look something like thisYou could also hack up the
parselinemethod to recognize submodule prefixes for commands etc…