python - 如何多次动态调用命令的子命令?

标签 python command-line-interface python-click

我的 Click 7.0 应用程序有一组,有多个命令,由主 cli 函数调用,如下所示:

代码:

import sys
import click

@click.group()
def cli():
    """This is cli helptext"""
    click.echo('cli called')

@cli.group(chain=True, no_args_is_help=False)
@click.option('-r', '--repeat', default=1, type=click.INT, help='repeat helptext')
def chainedgroup(repeat):
    """This is chainedgroup helptext"""

    top = sys.argv[2]
    bottom = sys.argv[3:]
    click.echo('chainedgroup code called')

    for _ in range(repeat):
        chainedgroup.main(bottom, top, standalone_mode=False)

@chainedgroup.command()
def command1():
    """This is command1 helptext"""
    click.echo('command1 called')

@chainedgroup.command()
@click.option('-o', '--option')
def command2(option):
    """This is command2 helptext"""
    click.echo('command2 called with {0}'.format(option))

运行:

$ testcli chainedgroup --repeat 2 command1
$ testcli chainedgroup -r 3 command1 command2 -o test

预期结果:

cli called
chainedgroup code called
command1 called
command1 called
----------
cli called
chainedgroup code called
command1 called
command2 called with test
command1 called
command2 called with test
command1 called
command2 called with test

实际结果:

案例#1 给出了Missing command 错误,而案例#2 则以RecursionError 结束。

我确定我确定Command.main()是正确的调用方法。我做错了什么?

最佳答案

如果您创建自定义 click.Group 类,则可以重写 invoke() 方法来多次调用命令。

自定义类:

class RepeatMultiCommand(click.Group):
    def invoke(self, ctx):
        old_callback = self.callback

        def new_callback(*args, **kwargs):
            # only call the group callback once
            if repeat_number == 0:
                return old_callback(*args, **kwargs)
        self.callback = new_callback

        # call invoke the desired number of times
        for repeat_number in range(ctx.params['repeat']):
            new_ctx = copy.deepcopy(ctx)
            super(RepeatMultiCommand, self).invoke(new_ctx)

        self.callback = old_callback

使用自定义类:

将带有 cls 参数的自定义类传递给 .group() 装饰器,如下所示:

@cli.group(chain=True, no_args_is_help=False, cls=RepeatMultiCommand)
@click.option('-r', '--repeat', default=1, type=click.INT,
              help='repeat helptext')
def chainedgroup(repeat):
    ....

这是如何工作的?

这是有效的,因为 click 是一个设计良好的 OO 框架。 @click.group() 装饰器通常会实例化 click.Group 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Group 并覆盖所需的方法是一件相对容易的事情。

在这种情况下,我们重写click.Group.invoke()。在我们的 invoke() 中,我们 Hook 组回调,以便我们只能调用它一次,然后我们将 super().invoke() 称为 重复次数。

测试代码:

import click
import copy
import sys

@click.group()
def cli():
    """This is cli helptext"""
    click.echo('cli called')


@cli.group(chain=True, no_args_is_help=False, cls=RepeatMultiCommand)
@click.option('-r', '--repeat', default=1, type=click.INT,
              help='repeat helptext')
def chainedgroup(repeat):
    """This is chainedgroup helptext"""
    click.echo('chainedgroup code called')


@chainedgroup.command()
def command1():
    """This is command1 helptext"""
    click.echo('command1 called')


@chainedgroup.command()
@click.option('-o', '--option')
def command2(option):
    """This is command2 helptext"""
    click.echo('command2 called with {0}'.format(option))


if __name__ == "__main__":
    commands = (
        'chainedgroup --repeat 2 command1',
        'chainedgroup -r 3 command1 command2 -o test',
        'chainedgroup command1',
        'chainedgroup --help',
        '--help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> chainedgroup --repeat 2 command1
cli called
chainedgroup code called
command1 called
command1 called
-----------
> chainedgroup -r 3 command1 command2 -o test
cli called
chainedgroup code called
command1 called
command2 called with test
command1 called
command2 called with test
command1 called
command2 called with test
-----------
> chainedgroup command1
cli called
chainedgroup code called
command1 called
-----------
> chainedgroup --help
cli called
Usage: test.py chainedgroup [OPTIONS] COMMAND1 [ARGS]... [COMMAND2
                            [ARGS]...]...

  This is chainedgroup helptext

Options:
  -r, --repeat INTEGER  repeat helptext
  --help                Show this message and exit.

Commands:
  command1  This is command1 helptext
  command2  This is command2 helptext
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  This is cli helptext

Options:
  --help  Show this message and exit.

Commands:
  chainedgroup  This is chainedgroup helptext

关于python - 如何多次动态调用命令的子命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56470525/

相关文章:

python - 如何在 Python 中使用 MATLAB 中的 unique(a, 'rows' )?

python - 在 python x64 上安装 TA-Lib

npm - 如何使用 "yarn"或 "npm"列出特定类型的依赖项

python - 使用 Python Click 创建分层命令

python - 代码适用于一个函数,但不适用于两个函数

python - 旋转数据框后检索正常数据框

python - 带有 pandas 的日期正则表达式过滤器不起作用

linux - 如何编写全屏 Linux 控制台应用程序/脚本?

postgresql - 使用 Heroku CLI、Postgres 时出现 SQL 语法错误

python - 在点击中弃用参数别名的正确方法