繁体   English   中英

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

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

我正在使用 cmd2 模块编写 python 命令行工具,该模块是 cmd 的增强版本。 该工具是一个管理应用程序,用于管理多个子模块。

我想构造代码,使每个子模块都有自己的 class 负责提供可以在该模块上执行的命令。 但鉴于命令 class 的工作原理,我不确定如何构建它。

所以我想要的是:

import cmd

class ConsoleApp(cmd.Cmd):

    # this is the main app and should get the commands from the sub-modules

app = ConsoleApp()
app.cmdloop()

然后将单独定义子模块。

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"

我该如何构建它以便主应用程序从子模块中获取命令?

谢谢,乔恩

将 SubModules 构建为主 ConsoleApp 的插件可能会有一些运气。 您需要在 ConsoleApp 上使用一些新方法。 add_command_module(self, klass)这样的东西,它只会 append 将 klass(例如 SubModuleA)添加到 ConsoleApp 中的某个列表中。

然后在 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)

您还可以破解parseline方法来识别命令等的子模块前缀......

暂无
暂无

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

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