在 Python 的 argparse 中多次使用相同的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36166225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the same option multiple times in Python's argparse
提问by John Allard
I'm trying to write a script that accepts multiple input sources and does something to each one. Something like this
我正在尝试编写一个脚本,该脚本接受多个输入源并对每个输入源执行一些操作。像这样的东西
./my_script.py \
-i input1_url input1_name input1_other_var \
-i input2_url input2_name input2_other_var \
-i input3_url input3_name
# notice inputX_other_var is optional
But I can't quite figure out how to do this using argparse
. It seems that it's set up so that each option flag can only be used once. I know how to associate multiple arguments with a single option (nargs='*'
or nargs='+'
), but that still won't let me use the -i
flag multiple times. How do I go about accomplishing this?
但我不太清楚如何使用argparse
. 它似乎设置为每个选项标志只能使用一次。我知道如何将多个参数与单个选项(nargs='*'
或nargs='+'
)相关联,但这仍然不会让我-i
多次使用该标志。我该如何去完成这个?
Just to be clear, what I would like in the end is a list of lists of strings. So
为了清楚起见,我最终想要的是一个字符串列表列表。所以
[["input1_url", "input1_name", "input1_other"],
["input2_url", "input2_name", "input2_other"],
["input3_url", "input3_name"]]
回答by hpaulj
Here's a parser that handles a repeated 2 argument optional - with names defined in the metavar
:
这是一个解析器,它处理重复的 2 个可选参数 - 名称定义在metavar
:
parser=argparse.ArgumentParser()
parser.add_argument('-i','--input',action='append',nargs=2,
metavar=('url','name'),help='help:')
In [295]: parser.print_help()
usage: ipython2.7 [-h] [-i url name]
optional arguments:
-h, --help show this help message and exit
-i url name, --input url name
help:
In [296]: parser.parse_args('-i one two -i three four'.split())
Out[296]: Namespace(input=[['one', 'two'], ['three', 'four']])
This does not handle the 2 or 3 argument
case (though I wrote a patch some time ago for a Python bug/issue that would handle such a range).
这不能处理这种2 or 3 argument
情况(尽管我前段时间为 Python 错误/问题编写了一个补丁来处理这样的范围)。
How about a separate argument definition with nargs=3
and metavar=('url','name','other')
?
用nargs=3
和单独定义参数怎么样metavar=('url','name','other')
?
The tuple metavar
can also be used with nargs='+'
and nargs='*'
; the 2 strings are used as [-u A [B ...]]
or [-u [A [B ...]]]
.
元组metavar
也可以与nargs='+'
and一起使用nargs='*'
;2 个字符串用作[-u A [B ...]]
or [-u [A [B ...]]]
。
回答by Amir
This is simple; just add both action='append'
and nargs='*'
(or '+'
).
这很简单;只需添加action='append'
和nargs='*'
(或'+'
)。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', action='append', nargs='+')
args = parser.parse_args()
Then when you run it, you get
然后当你运行它时,你得到
In [32]: run test.py -i input1_url input1_name input1_other_var -i input2_url i
...: nput2_name input2_other_var -i input3_url input3_name
In [33]: args.i
Out[33]:
[['input1_url', 'input1_name', 'input1_other_var'],
['input2_url', 'input2_name', 'input2_other_var'],
['input3_url', 'input3_name']]
回答by chepner
-i
should be configured to accept 3 arguments and to use the append
action.
-i
应配置为接受 3 个参数并使用该append
操作。
>>> p = argparse.ArgumentParser()
>>> p.add_argument("-i", nargs=3, action='append')
_AppendAction(...)
>>> p.parse_args("-i a b c -i d e f -i g h i".split())
Namespace(i=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
To handle an optional value, you might try using a simple custom type. In this case, the argument to -i
is a single comma-delimited string, with the number of splits limited to 2. You would need to post-process the values to ensure there are at least two values specified.
要处理可选值,您可以尝试使用简单的自定义类型。在这种情况下,to 的参数-i
是一个逗号分隔的字符串,拆分的数量限制为 2。您需要对这些值进行后处理以确保至少指定了两个值。
>>> p.add_argument("-i", type=lambda x: x.split(",", 2), action='append')
>>> print p.parse_args("-i a,b,c -i d,e -i g,h,i,j".split())
Namespace(i=[['a', 'b', 'c'], ['d', 'e'], ['g', 'h', 'i,j']])
For more control, define a custom action. This one extends the built-in _AppendAction
(used by action='append'
), but just does some range checking on the number of arguments given to -i
.
如需更多控制,请定义自定义操作。这个扩展了内置函数_AppendAction
(由 使用action='append'
),但只是对提供给 的参数数量进行一些范围检查-i
。
class TwoOrThree(argparse._AppendAction):
def __call__(self, parser, namespace, values, option_string=None):
if not (2 <= len(values) <= 3):
raise argparse.ArgumentError(self, "%s takes 2 or 3 values, %d given" % (option_string, len(values)))
super(TwoOrThree, self).__call__(parser, namespace, values, option_string)
p.add_argument("-i", nargs='+', action=TwoOrThree)