我正在尝试使用 Python Cmd 类构建一个 CLI(面向行的命令解释器),支持 2 种或更多模式,每种模式都有不同的命令集,以及在它们之间切换的命令。
目前,我使用每种模式的 2 个单独的类实现了 2 种模式,然后我设置下一个类在状态变量中执行:
class OpMode(Cmd):
def do_show(self, line):
:
def do_configure(self, line): # switch to ConfigMode
ctx.state = 'config'
return True
class ConfigMode(Cmd):
def do_set(self, line):
:
def do_exit(self, line): # go back to OpMode
ctx.state = 'op'
return True
# in main ...
while 1:
if ctx.state == 'op':
opcli.cmdloop()
elif ctx.state == 'conf':
confcli.cmdloop()
else:
break
有没有办法用单个 Cmd 类实现同样的事情?
最佳答案
使用单个 cmd 实例不会改进您的代码。您可以在 Cmd 类中跟踪您的状态,然后针对每个命令操作相应地调整您的响应。
但是,您可能想要的是不同状态之间更清晰的转换。您可以按如下方式执行此操作:
def do_configure(self, line):
config = ConfigMode(...)
config.cmdloop()
关于python - 具有 Python Cmd 类的面向行命令解释器的多种模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484365/