[英]How to release an application write by Python (which has structure folder) to user
[英]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.