同时使用多个选项或n

2024-04-25 03:53:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想同时使用几个选项,或者完全不使用,正如标题所说,但是我的方法看起来比较难看,我想知道是否有一种更干净的方法来实现这一点。此外,我还研究了this,关于如何在argparse中实现它,但是如果可能的话,我想在click中实现它(我试图避免使用nargs=[...])。你知道吗

到目前为止,我得到的是:

@click.group(invoke_without_command=True, no_args_is_help=True)
@click.option(
    "-d",
    "--group-dir",
    type=click.Path(),
    default="default",
    help='the directory to find the TOML file from which to run multiple jobs at the same time; defaults to the configuration directory of melmetal: "~/.melmetal" on Unix systems, and "C:\\Users\\user\\.melmetal" on Windows',
)
@click.option("-f", "--group-file", help="the TOML file name")
@click.option(
    "-n", "--group-name", help="name of the group of jobs"
)
@click.option(
    "--no-debug",
    is_flag=True,
    type=bool,
    help="prevent logging from being output to the terminal",
)
@click.pass_context
@logger.catch
def main(ctx, group_dir, group_file, group_name, no_debug):

    options = [group_file, group_name]
    group_dir = False if not any(options) else group_dir
    options.append(group_dir)

    if not any(options):
        pass
    elif not all(options):
        logger.error(
            colorize("red", "Sorry; you must use all options at once.")
        )
        exit(1)
    else:
        [...]

第二个例子是:

if any(createStuff):
    if not all(createStuff):
        le(
            colorize("red", 'Sorry; you must use both the "--config-dir" and "--config-file" options at once.')
        )
        exit(1)
elif any(filtered):
    if len(filtered) is not len(drbc):
        le(
            colorize("red", 'Sorry; you must use all of "--device", "--repo-name", "--backup-type", and "--config-dir" at once.')
        )
        exit(1)
else:
    ctx = click.get_current_context()
    click.echo(ctx.get_help())
    exit(0)

当没有给出子命令时,如何获得帮助文本来显示?据我所知,这应该是自动发生的,但对于我的代码,它会自动转到主函数。我的解决方法的一个例子在第二个例子中,即在else语句下。你知道吗


Tags: ofthetonameifdirgroupnot
1条回答
网友
1楼 · 发布于 2024-04-25 03:53:19

您可以通过构建从click.Option派生的自定义类来强制使用组中的所有选项,并在该类中使用click.Option.handle_parse_result()方法,如:

自定义选项类:

import click

class GroupedOptions(click.Option):
    def __init__(self, *args, **kwargs):
        self.opt_group = kwargs.pop('opt_group')
        assert self.opt_group, "'opt_group' parameter required"
        super(GroupedOptions, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        if self.name in opts:
            opts_in_group = [param.name for param in ctx.command.params
                             if isinstance(param, GroupedOptions) and
                             param.opt_group == self.opt_group]

            missing_specified = tuple(name for name in opts_in_group
                                      if name not in opts)

            if missing_specified:
                raise click.UsageError(
                    "Illegal usage: When using option '{}' must also use "
                    "all of options {}".format(self.name, missing_specified)
                )

        return super(GroupedOptions, self).handle_parse_result(
            ctx, opts, args)

使用自定义类:

要使用自定义类,请将cls参数传递给click.option装饰器,如下所示:

@click.option(' opt1', cls=GroupedOptions, opt_group=1)

另外,给出带有opt_group参数的选项组编号。你知道吗

这是怎么回事?

这是因为click是一个设计良好的OO框架。@click.option()修饰符通常实例化一个click.Option对象,但允许用cls参数覆盖此行为。因此,在我们自己的类中从click.Option继承并超越所需的方法是一件相对容易的事情。你知道吗

在本例中,我们跳过click.Option.handle_parse_result(),并检查是否指定了组中的其他选项。你知道吗

注意:这个答案的灵感来自this answer

测试代码:

@click.command()
@click.option(' opt1', cls=GroupedOptions, opt_group=1)
@click.option(' opt2', cls=GroupedOptions, opt_group=1)
@click.option(' opt3', cls=GroupedOptions, opt_group=1)
@click.option(' opt4', cls=GroupedOptions, opt_group=2)
@click.option(' opt5', cls=GroupedOptions, opt_group=2)
def cli(**kwargs):
    for arg, value in kwargs.items():
        click.echo("{}: {}".format(arg, value))

if __name__ == "__main__":
    commands = (
        ' opt1=x',
        ' opt4=a',
        ' opt4=a  opt5=b',
        ' opt1=x  opt2=y  opt3=z  opt4=a  opt5=b',
        ' 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)]
     -
>  opt1=x
Error: Illegal usage: When using option 'opt1' must also use all of options ('opt2', 'opt3')
     -
>  opt4=a
Error: Illegal usage: When using option 'opt4' must also use all of options ('opt5',)
     -
>  opt4=a  opt5=b
opt4: a
opt5: b
opt1: None
opt2: None
opt3: None
     -
>  opt1=x  opt2=y  opt3=z  opt4=a  opt5=b
opt1: x
opt2: y
opt3: z
opt4: a
opt5: b
     -
>  help
Usage: test.py [OPTIONS]

Options:
   opt1 TEXT
   opt2 TEXT
   opt3 TEXT
   opt4 TEXT
   opt5 TEXT
   help       Show this message and exit.
     -
> 
opt1: None
opt2: None
opt3: None
opt4: None
opt5: None

相关问题 更多 >