【问题标题】:nargs=* equivalent for options in Clicknargs=* 等效于 Click 中的选项
【发布时间】:2018-01-22 23:16:54
【问题描述】:

对于 Click 中的可选参数,是否有与 argparsenargs='*' 等效的功能?

我正在编写一个命令行脚本,其中一个选项需要能够接受无限数量的参数,例如:

foo --users alice bob charlie --bar baz

所以users 将是['alice', 'bob', 'charlie']bar 将是'baz'

argparse 中,我可以通过设置nargs='*' 来指定多个可选参数来收集它们后面的所有参数。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--users', nargs='*')
>>> parser.add_argument('--bar')
>>> parser.parse_args('--users alice bob charlie --bar baz'.split())
Namespace(bar='baz', users=['alice', 'bob', 'charlie'])

我知道 Click 允许您通过设置 nargs=-1 来指定 accept unlimited inputs 的参数,但是当我尝试将可选参数的 nargs 设置为 -1 时,我得到:

TypeError: 选项不能有参数

有没有办法让 Click 接受一个选项的未指定数量的参数?

更新:

我需要能够在接受无限参数的选项之后指定选项。

更新:

@Stephen Rauch 的回答回答了这个问题。但是,我不建议使用我在这里要求的方法。我的功能请求是intentionally not implemented in Click,因为它可能导致意外行为。 Click's recommended approach is to use multiple=True:

@click.option('-u', '--user', 'users', multiple=True)

在命令行中,它看起来像:

foo -u alice -u bob -u charlie --bar baz

【问题讨论】:

    标签: python python-3.x python-click


    【解决方案1】:

    实现您所追求的一种方法是从 click.Option 继承,并自定义解析器。

    自定义类:

    import click
    
    class OptionEatAll(click.Option):
    
        def __init__(self, *args, **kwargs):
            self.save_other_options = kwargs.pop('save_other_options', True)
            nargs = kwargs.pop('nargs', -1)
            assert nargs == -1, 'nargs, if set, must be -1 not {}'.format(nargs)
            super(OptionEatAll, self).__init__(*args, **kwargs)
            self._previous_parser_process = None
            self._eat_all_parser = None
    
        def add_to_parser(self, parser, ctx):
    
            def parser_process(value, state):
                # method to hook to the parser.process
                done = False
                value = [value]
                if self.save_other_options:
                    # grab everything up to the next option
                    while state.rargs and not done:
                        for prefix in self._eat_all_parser.prefixes:
                            if state.rargs[0].startswith(prefix):
                                done = True
                        if not done:
                            value.append(state.rargs.pop(0))
                else:
                    # grab everything remaining
                    value += state.rargs
                    state.rargs[:] = []
                value = tuple(value)
    
                # call the actual process
                self._previous_parser_process(value, state)
    
            retval = super(OptionEatAll, self).add_to_parser(parser, ctx)
            for name in self.opts:
                our_parser = parser._long_opt.get(name) or parser._short_opt.get(name)
                if our_parser:
                    self._eat_all_parser = our_parser
                    self._previous_parser_process = our_parser.process
                    our_parser.process = parser_process
                    break
            return retval
    

    使用自定义类:

    要使用自定义类,请将cls 参数传递给@click.option() 装饰器,例如:

    @click.option("--an_option", cls=OptionEatAll)
    

    或者如果希望该选项将占用整个命令行的其余部分,而不考虑其他选项:

    @click.option("--an_option", cls=OptionEatAll, save_other_options=False)
    

    这是如何工作的?

    这是可行的,因为 click 是一个设计良好的 OO 框架。 @click.option() 装饰器通常实例化一个 click.Option 对象,但允许使用 cls 参数覆盖此行为。所以这是一个相对 在我们自己的类中从 click.Option 继承并覆盖所需的方法很容易。

    在这种情况下,我们覆盖 click.Option.add_to_parser() 并且猴子修补解析器,以便我们可以 如果需要,可以吃多个代币。

    测试代码:

    @click.command()
    @click.option('-g', 'greedy', cls=OptionEatAll, save_other_options=False)
    @click.option('--polite', cls=OptionEatAll)
    @click.option('--other')
    def foo(polite, greedy, other):
        click.echo('greedy: {}'.format(greedy))
        click.echo('polite: {}'.format(polite))
        click.echo('other: {}'.format(other))
    
    
    if __name__ == "__main__":
        commands = (
            '-g a b --polite x',
            '-g a --polite x y --other o',
            '--polite x y --other o',
            '--polite x -g a b c --other o',
            '--polite x --other o -g a b c',
            '-g a b c',
            '-g a',
            '-g',
            'extra',
            '--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)
                foo(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)]
    -----------
    > -g a b --polite x
    greedy: ('a', 'b', '--polite', 'x')
    polite: None
    other: None
    -----------
    > -g a --polite x y --other o
    greedy: ('a', '--polite', 'x', 'y', '--other', 'o')
    polite: None
    other: None
    -----------
    > --polite x y --other o
    greedy: None
    polite: ('x', 'y')
    other: o
    -----------
    > --polite x -g a b c --other o
    greedy: ('a', 'b', 'c', '--other', 'o')
    polite: ('x',)
    other: None
    -----------
    > --polite x --other o -g a b c
    greedy: ('a', 'b', 'c')
    polite: ('x',)
    other: o
    -----------
    > -g a b c
    greedy: ('a', 'b', 'c')
    polite: None
    other: None
    -----------
    > -g a
    greedy: ('a',)
    polite: None
    other: None
    -----------
    > -g
    Error: -g option requires an argument
    -----------
    > extra
    Usage: test.py [OPTIONS]
    
    Error: Got unexpected extra argument (extra)
    -----------
    > --help
    Usage: test.py [OPTIONS]
    
    Options:
      -g TEXT
      --polite TEXT
      --other TEXT
      --help         Show this message and exit.
    

    【讨论】:

    • 这太棒了。非常感谢您抽出宝贵时间发布此答案!
    • 这似乎在 Click v8 中被破坏了
    • @KlemenTusar,我刚刚通过单击 8.0.1 重新运行了测试代码,并从上面得到了与 w/6.7 完全相同的结果。也许你可以写一个问题来记录你认为有什么问题?
    • @StephenRauch 我仍在调查,但老实说,这里是我的一个包的 GitHub 问题,它使用了github.com/techouse/mysql-to-sqlite3/issues/15 以上的解决方案。似乎与 Click 7.1.2 但不是 8+ 一起工作正常。我会继续挖掘并报告:)
    • 它似乎与这个点击问题github.com/pallets/click/issues/2012有关,只需在点击选项上定义声明type=tuple就可以解决它。
    【解决方案2】:

    你可以使用这个技巧。

    import click
    
    @click.command()
    @click.option('--users', nargs=0, required=True)
    @click.argument('users', nargs=-1)
    @click.option('--bar')
    def fancy_command(users, bar):
        users_str = ', '.join(users)
        print('Users: {}. Bar: {}'.format(users_str, bar))
    
    if __name__ == '__main__':
        fancy_command()
    

    添加带有所需名称且无参数 nargs=0 的假 option,然后添加带有无限参数的“argument”nargs=-1

    $ python foo --users alice bob charlie --bar baz
    Users: alice, bob, charlie. Bar: baz
    

    但要小心其他选项:

    $ python foo --users alice bob charlie --bar baz faz
    Users: alice, bob, charlie, faz. Bar: baz
    

    【讨论】:

    • 但在此设置中,可以完全省略 --users 标志。不确定这是否是预期的。
    • 谢谢你,@MarSoft!错过了!更改了上面的代码,添加了required=True。现在不可能省略---users。不幸的是,标志字符串可以省略。相同的结果:$ python foo --users alice bob charlie --bar baz faz$ python foo alice bob charlie --bar baz faz
    【解决方案3】:

    我遇到了同样的问题。我没有使用 n 个参数实现单个命令行选项,而是决定使用多个相同的命令行选项,并让 Click 在后台从参数中创建一个元组。我最终认为,如果 Click 不支持它,那么这个决定可能是有充分理由的。

    https://click.palletsprojects.com/en/7.x/options/#multiple-options

    这是我所说的一个例子:

    在分隔符上拆分而不是传递单个字符串参数:

    commit -m foo:bar:baz
    

    我选择使用这个:

    commit -m foo -m bar -m baz
    

    这里是源代码:

    @click.command()
    @click.option('--message', '-m', multiple=True)
    def commit(message):
        click.echo('\n'.join(message))
    

    这需要输入更多内容,但我确实认为它使 CLI 更加用户友好和强大。

    【讨论】:

    • 这是界面的正确答案,也是我最终选择的那个。 nargs=+ 是一个不错的 hack,但它通常会鼓励糟糕的 CLI 设计
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2018-01-17
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多