【问题标题】:Multiple modes for line-oriented command interpreters with Python Cmd class具有 Python Cmd 类的面向行的命令解释器的多种模式
【发布时间】:2013-08-28 09:39:28
【问题描述】:

我正在尝试使用支持 2 种或更多模式的 Python Cmd 类构建 CLI(面向行的命令解释器),每种模式都有不同的命令集,并带有在它们之间切换的命令。

目前我实现了 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 类实现相同的功能?

【问题讨论】:

    标签: python shell cmd command-line-interface


    【解决方案1】:

    使用单个 cmd 实例不会改进您的代码。您可以在 Cmd 类中跟踪您的状态,然后为每个命令操作相应地调整您的响应。

    但是,您可能想要的是不同状态之间的更清晰的过渡。你可以这样做:

    def do_configure(self, line):
        config = ConfigMode(...)
        config.cmdloop()
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      相关资源
      最近更新 更多