使用 cmd 模块:如何在“帮助”中记录子命令并与自动完成集成?

Using cmd module: how to have sub-commands documented in `help` and integrated with autocomplete?

我正在使用 cmd 模块并有一个名为 server 的命令(方法 do_server()),它具有开箱即用的自动完成功能(我在 macOS 上)。这一切都很好,并且按预期工作。但是,如果我还想在 server 命令上另外使用子命令,事情不会像我需要的那样进行。

我需要以下内容:
- 子命令也应与 help 命令集成(输入 help 时不应显示,因为它们不是一级命令,但应在输入 help server 时显示)
- 子命令也应该与自动完成集成

目前我没有看到一种开箱即用的定义子命令的方法。我需要将它们实现为不理想的命令的参数。

我的问题是,如何使用 help 实现子命令的自动文档记录并自动完成,以便它尽可能与 cmd 集成?

对于这个例子,我想更好地将 connect 集成为一个子命令:

from cmd import Cmd


class Tansanit(Cmd):

    def do_server(self, args):
        """ Show server info """
        print("Some server details")

        if args and args == "connect":
            print("Connect to the server")

    def do_quit(self, args):
        """ Quit CLI """
        raise SystemExit


if __name__ == '__main__':
    t = Tansanit()
    t.prompt = "> "
    t.cmdloop()

我更喜欢这样的东西:

from cmd import Cmd


class Tansanit(Cmd):

    def do_server(self, args):
        """ Show server info """
        print("Some server details")

    def do_server_connect(self, args):
        """ Connect to server """
        print("Connect to the server")

    def do_quit(self, args):
        """ Quit CLI """
        raise SystemExit


if __name__ == '__main__':
    t = Tansanit()
    t.prompt = "> "
    t.cmdloop()

很遗憾,这是不可能的。

可以找到相关信息here

sub-commands

的自动完成

The interpreter is able to process completion for commands names, but for commands arguments you will have to help it. For the command xxx, this is done by defining a complete_xxx method. For example, if you have defined a color command, the completion method for this command could be:

_AVAILABLE_COLORS = ('blue', 'green', 'yellow', 'red', 'black')
def complete_color(self, text, line, begidx, endidx):
    return [i for i in _AVAILABLE_COLORS if i.startswith(text)]

The complete_xxx method takes four arguments:

text is the string we are matching against, all returned matches must begin with it line is is the current input line begidx is the beginning index in the line of the text being matched endidx is the end index in the line of the text being matched It should return a list (possibly empty) of strings representing the possible completions. The arguments begidx and endidx are useful when completion depends on the position of the argument.

help 对于 sub-commands

You can also define help for topics that are not related to commands:

def help_introduction(self):
    print 'introduction'
    print 'a good place for a tutorial'

这并不完美,因为帮助将被归类为 undocumented commands,但它用于争论。但也许总比什么都没有好。