nargs = *等价于Click中的选项 [英] nargs=* equivalent for options in Click

查看:76
本文介绍了nargs = *等价于Click中的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there an equivalent to argparse's nargs='*' functionality for optional arguments in Click?

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

I am writing a command line script, and one of the options needs to be able to take an unlimited number of arguments, like:

foo --users alice bob charlie --bar baz

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

argparse 中,我可以指定多个可选参数来通过设置nargs='*'来收集所有跟在其后的参数.

In argparse, I can specify multiple optional arguments to collect all of the arguments that follow them by setting 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,但是当我尝试将可选参数的nargs设置为-1时,我得到:

I know Click allows you to specify an argument to accept unlimited inputs by setting nargs=-1, but when I try to set an optional argument's nargs to -1, I get:

TypeError:选项不能包含nargs< 0

TypeError: Options cannot have nargs < 0

有没有一种方法可以使Click接受选项的未指定数量的参数?

Is there a way to make Click accept an unspecified number of arguments for an option?

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

I need to be able to specify options after the option that takes unlimited arguments.

@Stephen Rauch的答案回答了这个问题.但是,我不建议您使用此处要求的方法.我的功能请求是故意没有在Click中实现,因为它会导致意外的行为. Click推荐的方法是使用multiple=True :

@Stephen Rauch's answer answers this question. However, I don't recommend using the approach I ask for here. My feature request is intentionally not implemented in Click, since it can result in unexpected behaviors. Click's recommended approach is to use multiple=True:

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

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

And in the command line, it will look like:

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

推荐答案

一种处理方法,就是从click.Option继承,并自定义解析器.

One way to approach what you are after is to inherit from click.Option, and customize the parser.

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()装饰器,例如:

Using Custom Class:

To use the custom class, pass the cls parameter to @click.option() decorator like:

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

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

or if it is desired that the option will eat the entire rest of the command line, not respecting other options:

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

这是如何工作的?

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

How does this work?

This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods.

在这种情况下,我们越过click.Option.add_to_parser(),猴子对解析器进行修补,以便我们可以 如果需要,可以吃多个令牌.

In this case we over ride click.Option.add_to_parser() and the monkey patch the parser so that we can eat more than one token if desired.

@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.

这篇关于nargs = *等价于Click中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆