python - python中的互斥选项组单击

标签 python python-click

如何在 Click 中创建互斥选项组?我想要么接受标志“--all”,要么接受带有“--color red”等参数的选项。

最佳答案

我最近遇到了同样的用例;这就是我想出的。对于每个选项,您可以给出一个冲突选项列表。

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 参数:

@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 包含上面的代码并显示运行它的输出。

如果这对您不起作用,还有一些(已关闭的)问题在 click github 页面上提到了这一点,其中包含一些您可能可以使用的想法。

关于python - python中的互斥选项组单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37310718/

相关文章:

java - Web 挖掘或抓取或爬行?我应该使用什么工具/库?

python - 如何使用 Python(和 boto)克隆 Amazon S3 中的 key ?

python点击,使选项值可选

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

Python click,你能把 -h 作为别名吗

python - 如何使用 scikit-learn 创建我自己的数据集?

python - 输出一列字数大于 3 的所有行

python - 点击: NameError: name not defined

python - 在点击命令之上装饰

python - 我已经安装了MSYS2和Anaconda3,那么如何在MSYS2上使用conda呢?