本文介绍了在 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 或 3 参数 的情况(尽管我前段时间为 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