Python argparse:组合"choices","nargs"和"default"时出现类型不一致 [英] Python argparse: type inconsistencies when combining 'choices', 'nargs' and 'default'
问题描述
我有以下python程序:
I have the following python program:
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('arg', choices=['foo', 'bar', 'baz'], default='foo', nargs='*')
args = parser.parse_args()
print(args)
如果我这样调用程序:
./prog.py
输出为
Namespace(arg='foo')
但是如果我使用 foo
作为参数来调用程序:
But if I invoke the program with foo
as an argument:
./prog.py foo
输出为
Namespace(arg=['foo'])
问题
如何获取 arg
的默认值以成为 list
?
How can I get arg
's default value to become a list
?
我已经尝试
我尝试设置 default = ['foo']
,但结果是:
I've tried setting default=['foo']
but that results in:
prog.py: error: argument arg: invalid choice: ['foo'] (choose from 'foo', 'bar', 'baz')
推荐答案
这是一个古老但开放的bug/问题的副本
This is a duplicate of an old, but open, bug/issue
http://bugs.python.org/issue9625 ( argparse:默认值问题用于使用选项时的变量nargs
)
带有 *
的 positional
得到一些特殊的处理.如果您不提供值,则默认值始终通过 choices
测试传递.
A positional
with *
gets some special handling. Its default is always passed through the choices
test if you don't provide values.
将其与可选
In [138]: p=argparse.ArgumentParser()
In [139]: a=p.add_argument('--arg',choices=['foo','bar','baz'],nargs='*')
In [140]: p.parse_args([])
Out[140]: Namespace(arg=None)
In [141]: a.default=['foo']
In [142]: p.parse_args([])
Out[142]: Namespace(arg=['foo'])
默认值未经测试即被接受:
The default is accepted without testing:
In [143]: a.default=['xxx']
In [144]: p.parse_args([])
Out[144]: Namespace(arg=['xxx'])
相关代码为:
def _get_values(self, action, arg_strings):
...
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
建议的错误/问题补丁对该代码块进行了少量更改.
The proposed bug/issue patch makes a small change to this block of code.
这篇关于Python argparse:组合"choices","nargs"和"default"时出现类型不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!