本文介绍了在Python的argparse中多次使用相同的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,该脚本接受多个输入源并对每个输入源都执行某项操作.像这样

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

但是我不太清楚如何使用argparse来做到这一点.似乎已经设置好,因此每个选项标志只能使用一次.我知道如何将多个参数与单个选项(nargs='*'nargs='+')相关联,但这仍然不能让我多次使用-i标志.我该如何做到这一点?

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?

请明确一点,我最后想要的是一个字符串列表列表.所以

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"]]

推荐答案

这里是一个解析器,用于处理重复的2个可选参数-名称在metavar中定义:

Here's a parser that handles a repeated 2 argument optional - with names defined in the 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']])

这不能处理2 or 3 argument的情况(尽管我前段时间写了一个可处理该范围的Python错误/问题的补丁程序.)

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

使用nargs=3metavar=('url','name','other')的单独的参数定义如何?

How about a separate argument definition with nargs=3 and metavar=('url','name','other')?

元组metavar也可以与nargs='+'nargs='*'一起使用;这两个字符串用作[-u A [B ...]][-u [A [B ...]]].

The tuple metavar can also be used with nargs='+' and nargs='*'; the 2 strings are used as [-u A [B ...]] or [-u [A [B ...]]].

这篇关于在Python的argparse中多次使用相同的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 22:10