如何构造具有单独命令模块的python cmd应用程序
我正在使用cmd2模块编写python命令行工具,cmd2模块是cmd的增强版本。该工具是一个管理应用程序,用于管理多个子模块 我希望对代码进行结构化,以便每个子模块都有自己的类负责提供可在该模块上执行的命令。但鉴于command类的工作方式,我不确定如何构造它 所以我想要的是:如何构造具有单独命令模块的python cmd应用程序,python,Python,我正在使用cmd2模块编写python命令行工具,cmd2模块是cmd的增强版本。该工具是一个管理应用程序,用于管理多个子模块 我希望对代码进行结构化,以便每个子模块都有自己的类负责提供可在该模块上执行的命令。但鉴于command类的工作方式,我不确定如何构造它 所以我想要的是: import cmd class ConsoleApp(cmd.Cmd): # this is the main app and should get the commands from the sub-m
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"
我如何构造它,以便主应用程序能够从子模块接收命令
谢谢,Jon您可能有幸将子模块构建为主控制台的插件。您需要在ConsoleApp上使用一些新方法。类似于
add\u command\u module(self,klass)
的东西只会将klass(例如子模块)附加到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
方法识别命令等的子模块前缀。您可能有幸将子模块构造为主控制台的插件。您需要在ConsoleApp上使用一些新方法。类似于add\u command\u module(self,klass)
的东西只会将klass(例如子模块)附加到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
方法来识别命令等的子模块前缀。不幸的是多重继承?可能是…我希望有一个替代方法。不幸的是多重继承?可能是…我希望有一个替代方法。当然。如果你最终制作出了这样的东西(而且效果很好),请分享。我也会有一些用途:)当然。如果你最终制作出了这样的东西(而且效果很好),请分享。我也有一些用途:)