python中的互斥选项组请点击 [英] Mutually exclusive option groups in python Click

查看:87
本文介绍了python中的互斥选项组请点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Click中创建一个互斥的选项组?我想接受标志"--all"或采用带有"--color red"等参数的选项.

How can I create a mutually exclusive option group in Click? I want to either accept the flag "--all" or take an option with a parameter like "--color red".

推荐答案

我最近也遇到了同样的用例.这就是我想出的.对于每个选项,您都可以列出冲突的选项.

I ran into this same use case recently; this is what I came up with. For each option, you can give a list of conflicting options.

from click import command, option, Option, UsageError


class MutuallyExclusiveOption(Option):
    def __init__(self, *args, **kwargs):
        self.mutually_exclusive = set(kwargs.pop('mutually_exclusive', []))
        help = kwargs.get('help', '')
        if self.mutually_exclusive:
            ex_str = ', '.join(self.mutually_exclusive)
            kwargs['help'] = help + (
                ' NOTE: This argument is mutually exclusive with '
                ' arguments: [' + ex_str + '].'
            )
        super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        if self.mutually_exclusive.intersection(opts) and self.name in opts:
            raise UsageError(
                "Illegal usage: `{}` is mutually exclusive with "
                "arguments `{}`.".format(
                    self.name,
                    ', '.join(self.mutually_exclusive)
                )
            )

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

然后使用常规的option装饰器,但传递cls参数:

Then use the regular option decorator but pass the cls argument:

@command(help="Run the command.")
@option('--jar-file', cls=MutuallyExclusiveOption,
        help="The jar file the topology lives in.",
        mutually_exclusive=["other_arg"])
@option('--other-arg',
        cls=MutuallyExclusiveOption,
        help="The jar file the topology lives in.",
        mutually_exclusive=["jar_file"])
def cli(jar_file, other_arg):
    print "Running cli."
    print "jar-file: {}".format(jar_file)
    print "other-arg: {}".format(other_arg)

if __name__ == '__main__':
    cli() 

这是要点 其中包含上面的代码,并显示了运行它的输出.

Here's a gist that includes the code above and shows the output from running it.

如果这对您不起作用,那么在单击github页面上还会有一些(封闭的)问题提及此问题,并提供了一些您可能可以使用的想法.

If that won't work for you, there's also a few (closed) issues mentioning this on the click github page with a couple of ideas that you may be able to use.

  • https://github.com/pallets/click/issues/257
  • https://github.com/pallets/click/issues/509

这篇关于python中的互斥选项组请点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆