python中的互斥选项组请点击

发布于 2021-01-29 15:27:28

如何在Click中创建互斥选项组?我想接受标志“ –all”或采用带有“ –color red”等参数的选项。

关注者
0
被浏览
179
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    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()
    

    这里的要点
    包括上面的代码,并显示了运行它的输出。

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看