我正在使用click(http://click.pocoo.org/3/)创建命令行应用程序,但是我不知道如何为该应用程序创建 shell 。
假设我正在编写一个名为test的程序,并且有名为subtest1和subtest2的命令

我能够使其在终端上正常工作,例如:

$ test subtest1
$ test subtest2

但是我在想的是 shell ,所以我可以这样做:
$ test
>> subtest1
>> subtest2

点击可以实现吗?

最佳答案

点击并不是不可能的,但是也没有内置的支持。首先,您需要通过将invoke_without_command=True传递到组装饰器中来使组回调在没有子命令的情况下可调用(如here所述)。然后,您的组回调将必须实现REPL。 Python在标准库中具有cmd框架来执行此操作。使click子命令在那里可用涉及覆盖cmd.Cmd.default,如下面的代码片段中所示。正确处理所有细节,例如help,应该在几行之内就可以完成。

import click
import cmd

class REPL(cmd.Cmd):
    def __init__(self, ctx):
        cmd.Cmd.__init__(self)
        self.ctx = ctx

    def default(self, line):
        subcommand = cli.commands.get(line)
        if subcommand:
            self.ctx.invoke(subcommand)
        else:
            return cmd.Cmd.default(self, line)

@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        repl = REPL(ctx)
        repl.cmdloop()

@cli.command()
def a():
    """The `a` command prints an 'a'."""
    print "a"

@cli.command()
def b():
    """The `b` command prints a 'b'."""
    print "b"

if __name__ == "__main__":
    cli()

10-07 19:48
查看更多