nargs =*等效于Click中的选项

jpy*_*ams 12 python python-3.x python-click

在Click中是否有与可选参数相同argparsenargs='*'功能?

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

foo --users alice bob charlie --bar baz
Run Code Online (Sandbox Code Playgroud)

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'])
Run Code Online (Sandbox Code Playgroud)

我知道Click允许你通过设置指定一个接受无限输入的参数nargs=-1,但当我尝试将可选参数设置nargs为-1时,我得到:

TypeError:选项的narg <0

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

更新:

我需要能够在带有无限参数的选项之后指定选项.

Ste*_*uch 14

解决后续问题的一种方法是从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
Run Code Online (Sandbox Code Playgroud)

使用自定义类:

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

@click.option("--an_option", cls=OptionEatAll)
Run Code Online (Sandbox Code Playgroud)

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

@click.option("--an_option", cls=OptionEatAll, save_other_options=False)
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?

这是有效的,因为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
Run Code Online (Sandbox Code Playgroud)

检测结果:

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.
Run Code Online (Sandbox Code Playgroud)

  • 它似乎与此 Click 问题有关 https://github.com/pallets/click/issues/2012 并且只需在单击选项上定义声明 `type=tuple` 即可修复此问题。 (4认同)
  • 这太棒了。非常感谢您花时间发表此答案! (2认同)

Nik*_*hko 8

你可以使用这个技巧。

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()
Run Code Online (Sandbox Code Playgroud)

添加option带有所需名称且无参数的fake nargs=0,然后添加带有无限制 args 的 'argument' nargs=-1

$ python foo --users alice bob charlie --bar baz
Users: alice, bob, charlie. Bar: baz
Run Code Online (Sandbox Code Playgroud)

但要小心其他选项:

$ python foo --users alice bob charlie --bar baz faz
Users: alice, bob, charlie, faz. Bar: baz
Run Code Online (Sandbox Code Playgroud)

  • 但是在这个设置中,完全可以省略 `--users` 标志。不确定这是否是预期的。 (2认同)

Aid*_*len 5

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

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

这是我所说的一个例子:

而不是传递单个字符串参数,而是在分隔符上进行分割:

commit -m foo:bar:baz
Run Code Online (Sandbox Code Playgroud)

我选择使用这个:

commit -m foo -m bar -m baz
Run Code Online (Sandbox Code Playgroud)

这是源代码:

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

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

  • 这是界面的正确答案,也是我最终选择的答案。`nargs=+` 是一个很好的 hack,但它通常会鼓励糟糕的 CLI 设计 (2认同)