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

时间:2019-06-06 03:24:13

标签: 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()是正确的调用方法。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

如果您创建自定义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

要使用自定义类:

通过.group()参数向cls装饰器传递自定义类,例如:

@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()中,我们钩住了组回调,以便只能将其调用一次,然后将super().invoke()调用repeat次。

测试代码:

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