使用Python和Click创建shell命令行应用程序

Fáb*_*lug 9 python command-line-interface python-click

我正在使用click(http://click.pocoo.org/3/)来创建命令行应用程序,但我不知道如何为此应用程序创建shell.
假设我正在编写一个名为test的程序,我有一个名为subtest1subtest2的命令

我能够从终端工作,如:

$ test subtest1
$ test subtest2
Run Code Online (Sandbox Code Playgroud)

但我在考虑的是一个shell,所以我可以这样做:

$ test  
>> subtest1  
>> subtest2
Run Code Online (Sandbox Code Playgroud)

点击可以实现吗?

fpb*_*bhb 15

这不是不可能的点击,但也没有内置的支持.首先,你必须做的是通过传递使你的组回调可调用无子invoke_without_command=True成团装饰(如描述在这里).那么你的组回调就必须实现一个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()
Run Code Online (Sandbox Code Playgroud)