gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:04:15 25 4
gpt4 key购买 nike

如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com