问题描述
我有以下 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
?
我试过了
我试过设置 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')
推荐答案
这是一个旧的但开放的错误/问题的副本
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.
将其与 optional
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'])
默认接受,无需测试:
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:组合“选择"、“nargs"和“默认"时键入不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!