带有单击的多个命令的命令行界面:将命令的未指定选项添加为字典

时间:2019-01-07 11:42:22

标签: python python-click

我有一个带有click的命令行界面,可实现多个命令。

现在,我想将未指定的命名选项传递到一个名为command1的命令中,例如选项的数量及其名称应能够灵活地变化。

import click


@click.group(chain=True)
@click.pass_context
def cli(ctx, **kwargs):
    return True


@cli.command()
@click.option('--command1-option1', type=str)
@click.option('--command1-option2', type=str)
@click.pass_context
def command1(ctx, **kwargs):
    """Add command1."""
    ctx.obj['command1_args'] = {}
    for k, v in kwargs.items():
        ctx.obj['command1_args'][k] = v
    return True


@cli.command()
@click.argument('command2-argument1', type=str)
@click.pass_context
def command2(ctx, **kwargs):
    """Add command2."""
    print(ctx.obj)
    print(kwargs)
    return True


if __name__ == '__main__':
    cli(obj={})

我已经像在forwarding unknown options中一样研究了this question,但问题是我必须在必须断言的第一个命令之后调用(chanin)其他命令。此调用必须有效,但可以为command1使用任意选项:

$python cli.py command1 --command1-option1 foo --command1-option2 bar command2 'hello'

那么我如何才能将未指定的命名选项添加到单个命令并同时(在此之后)调用(链接)另一个命令?

1 个答案:

答案 0 :(得分:1)

发现here的自定义类可以适应您的情况。

使用自定义类:

要使用自定义类,只需在click.command()装饰器中使用cls参数,例如:

AId

测试代码:

@cli.command(cls=AcceptAllCommand)
@click.pass_context
def command1(ctx, **kwargs):
    """Add command1."""
    ...

结果:

import click

class AcceptAllCommand(click.Command):

    def make_parser(self, ctx):
        """Hook 'make_parser' and allow the opt dict to find any option"""
        parser = super(AcceptAllCommand, self).make_parser(ctx)
        command = self

        class AcceptAllDict(dict):

            def __contains__(self, item):
                """If the parser does no know this option, add it"""

                if not super(AcceptAllDict, self).__contains__(item):
                    # create an option name
                    name = item.lstrip('-')

                    # add the option to our command
                    click.option(item)(command)

                    # get the option instance from the command
                    option = command.params[-1]

                    # add the option instance to the parser
                    parser.add_option(
                        [item], name.replace('-', '_'), obj=option)
                return True

        # set the parser options to our dict
        parser._short_opt = AcceptAllDict(parser._short_opt)
        parser._long_opt = AcceptAllDict(parser._long_opt)

        return parser


@click.group(chain=True)
@click.pass_context
def cli(ctx, **kwargs):
    """"""


@cli.command(cls=AcceptAllCommand)
@click.pass_context
def command1(ctx, **kwargs):
    """Add command1."""
    ctx.obj['command1_args'] = {}
    for k, v in kwargs.items():
        ctx.obj['command1_args'][k] = v


@cli.command()
@click.argument('command2-argument1', type=str)
@click.pass_context
def command2(ctx, **kwargs):
    """Add command2."""
    print(ctx.obj)
    print(kwargs)


if __name__ == "__main__":
    commands = (
        "command1 --cmd1-opt1 foo --cmd1-opt2 bar command2 hello",
        '--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(), obj={})

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