简体   繁体   English

如何构建具有单独命令模块的 python cmd 应用程序

[英]How to structure a python cmd application which has separate command modules

I'm writing a python command-line tool using the cmd2 module which is an enhanced version of cmd.我正在使用 cmd2 模块编写 python 命令行工具,该模块是 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.我想构造代码,使每个子模块都有自己的 class 负责提供可以在该模块上执行的命令。 But I'm not sure how to structure this given how the command class works.但鉴于命令 class 的工作原理,我不确定如何构建它。

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.将 SubModules 构建为主 ConsoleApp 的插件可能会有一些运气。 You'd need a couple of new methods on ConsoleApp.您需要在 ConsoleApp 上使用一些新方法。 Something like add_command_module(self, klass) which would just append the klass (SubModuleA for example) to some list inside ConsoleApp.add_command_module(self, klass)这样的东西,它只会 append 将 klass(例如 SubModuleA)添加到 ConsoleApp 中的某个列表中。

Then in ConsoleApp, override the onecmd method to look something like this然后在 ConsoleApp 中,覆盖onecmd方法,使其看起来像这样

def onecmd(self, line):
  if not line:
    return self.emptyline()
  if cmd is None:
    return self.default(line)
  self.lastcmd = line
  if cmd == '': 
    return self.default(line)
  else:
    # iterate over all submodules that have been added including ourselves
    # self.submodules would just be a list or set of all submodules as mentioned above
    func = None
    for submod in self.submodules:
      # just return the first match we find
      if hasattr(submod, 'do_%s' % cmd):
        func = getattr(submod, 'do_%s' % cmd)
        break # instead of breaking, you could also add up all the modules that have
              # this method, and tell the user to be more specific
    if func is not None:
      return func(arg)
    else:
      return self.default(line)

You could also hack up the parseline method to recognize submodule prefixes for commands etc...您还可以破解parseline方法来识别命令等的子模块前缀......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM