Argparse:如何处理可变数量的参数(nargs ='*') [英] Argparse: how to handle variable number of arguments (nargs='*')

查看:635
本文介绍了Argparse:如何处理可变数量的参数(nargs ='*')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为nargs='*'足以处理可变数量的参数.显然不是,而且我不了解此错误的原因.

I thought that nargs='*' was enough to handle a variable number of arguments. Apparently it's not, and I don't understand the cause of this error.

代码:

p = argparse.ArgumentParser()
p.add_argument('pos')
p.add_argument('foo')
p.add_argument('--spam', default=24, type=int, dest='spam')
p.add_argument('vars', nargs='*')

p.parse_args('1 2 --spam 8 8 9'.split())

我认为结果命名空间应该是Namespace(pos='1', foo='2', spam='8', vars=['8', '9']).相反,argparse会出现此错误:

I think the resulting namespace should be Namespace(pos='1', foo='2', spam='8', vars=['8', '9']). Instead, argparse gives this error:

usage: prog.py [-h] [--spam SPAM] pos foo [vars [vars ...]]
error: unrecognized arguments: 9 8

基本上,argparse不知道将这些附加参数放在哪里...为什么?

Basically, argparse doesn't know where to put those additional arguments... Why is that?

推荐答案

相关的Python错误是问题15112 .

The relevant Python bug is Issue 15112.

argparse: nargs='*'位置参数如果前面带有选项和另一个位置,则不接受任何项目

argparse: nargs='*' positional argument doesn't accept any items if preceded by an option and another positional

当argparse解析['1', '2', '--spam', '8', '8', '9']时,它首先尝试将['1','2']与尽可能多的位置参数匹配.使用您的参数,模式匹配字符串为AAA*:posfoo分别为1个参数,而vars为零参数(记住*表示ZERO_OR_MORE).

When argparse parses ['1', '2', '--spam', '8', '8', '9'] it first tries to match ['1','2'] with as many of the positional arguments as possible. With your arguments the pattern matching string is AAA*: 1 argument each for pos and foo, and zero arguments for vars (remember * means ZERO_OR_MORE).

['--spam','8']由您的--spam参数处理.由于vars已经设置为[],因此没有任何内容可以处理['8','9'].

['--spam','8'] are handled by your --spam argument. Since vars has already been set to [], there is nothing left to handle ['8','9'].

argparse的编程更改将检查是否0参数字符串满足该模式,但仍要解析optionals的情况.然后,它会延迟对该*参数的处理.

The programming change to argparse checks for the case where 0 argument strings is satisfying the pattern, but there are still optionals to be parsed. It then defers the handling of that * argument.

您可能可以通过以下方法解决此问题:首先使用remainder rel ="noreferrer"> parse_args .

You might be able to get around this by first parsing the input with parse_known_args, and then handling the remainder with another call to parse_args.

要完全自由地在位置之间散布可选内容,请在 issue 14191 中提出,建议使用parse_known_args仅带有optionals,然后是仅了解位置的parse_args.我发布的parse_intermixed_args函数可以在ArgumentParser子类中实现,而无需修改argparse.py代码本身.

To have complete freedom in interspersing optionals among positionals, in issue 14191, I propose using parse_known_args with just the optionals, followed by a parse_args that only knows about the positionals. The parse_intermixed_args function that I posted there could be implemented in an ArgumentParser subclass, without modifying the argparse.py code itself.

这是处理次解析器的一种方法.我采用了 parse_known_intermixed_args 函数,出于演示目的对其进行了简化,然后进行了它是解析器子类的parse_known_args函数.我不得不采取额外的步骤来避免递归.

Here's a way of handling subparsers. I've taken the parse_known_intermixed_args function, simplified it for presentation sake, and then made it the parse_known_args function of a Parser subclass. I had to take an extra step to avoid recursion.

最后,我更改了子解析器Action的_parser_class,因此每个子解析器都使用此替代项parse_known_args.另一种选择是子类_SubParsersAction,可能会修改其__call__.

Finally I changed the _parser_class of the subparsers Action, so each subparser uses this alternative parse_known_args. An alternative would be to subclass _SubParsersAction, possibly modifying its __call__.

from argparse import ArgumentParser

def parse_known_intermixed_args(self, args=None, namespace=None):
    # self - argparse parser
    # simplified from http://bugs.python.org/file30204/test_intermixed.py
    parsefn = super(SubParser, self).parse_known_args # avoid recursion

    positionals = self._get_positional_actions()
    for action in positionals:
        # deactivate positionals
        action.save_nargs = action.nargs
        action.nargs = 0

    namespace, remaining_args = parsefn(args, namespace)
    for action in positionals:
        # remove the empty positional values from namespace
        if hasattr(namespace, action.dest):
            delattr(namespace, action.dest)
    for action in positionals:
        action.nargs = action.save_nargs
    # parse positionals
    namespace, extras = parsefn(remaining_args, namespace)
    return namespace, extras

class SubParser(ArgumentParser):
    parse_known_args = parse_known_intermixed_args

parser = ArgumentParser()
parser.add_argument('foo')
sp = parser.add_subparsers(dest='cmd')
sp._parser_class = SubParser # use different parser class for subparsers
spp1 = sp.add_parser('cmd1')
spp1.add_argument('-x')
spp1.add_argument('bar')
spp1.add_argument('vars',nargs='*')

print parser.parse_args('foo cmd1 bar -x one 8 9'.split())
# Namespace(bar='bar', cmd='cmd1', foo='foo', vars=['8', '9'], x='one')

这篇关于Argparse:如何处理可变数量的参数(nargs ='*')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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