gpt4 book ai didi

python - nargs=* 相当于 Click 中的选项

转载 作者:太空狗 更新时间:2023-10-29 20:15:03 26 4
gpt4 key购买 nike

对于 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 允许您为 accept unlimited inputs 指定一个参数通过设置 nargs=-1,但是当我尝试将可选参数的 nargs 设置为 -1 时,我得到:

TypeError: Options cannot have nargs < 0

有没有办法让 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

最佳答案

实现您所追求的目标的一种方法是继承 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() 和猴子修补解析器,这样我们就可以如果需要,可以吃多个 token 。

测试代码:

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

关于python - nargs=* 相当于 Click 中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391777/

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