Python的`argparse`可以多次使用相同的选项,但将这些选项放入同一个列表中。

huangapple go评论87阅读模式
英文:

Python's argeparse using same option multiple times, but put those options in same list

问题

[
    input1, 
    input2, 
    input3, 
    input4, 
    input5,
    input6
]
英文:

In Python's argparse, using the same option multiple times puts those arguments in different lists. But I want those arguments on the same list.

The result I have got is:

# only the input portion
[
    [input1, input2],
    [input3, input4, input5],
    [input6]
]

My Code:

# myScript.py
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-i', action='append', nargs='+')
parser.add_argument('-o', action='append', nargs='*')
args = parser.parse_args()

Executing the code:

myScript.py -i input1 input2 -o output1 -i input3 input4 input5 -o output2 -i input6

The result I want is:

[
    input1, 
    input2, 
    input3, 
    input4, 
    input5,
    input6
]

答案1

得分: 2

要将这些参数放入同一个列表[]中我们必须在代码中使用action="extend"而不是action="append"因此无论我们使用该选项多少次我们都将在同一个单一列表中获得这些参数
英文:

To get those arguments in the same list[], we have to use action="extend" instead of action="append" in our code. So it doesn't matter how many time we use the option, we will get those arguments in the same single list.

[
    input1, 
    input2, 
    input3, 
    input4, 
    input5,
    input6
]

That means the code will be something like:

# myScript.py
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-i', action='extend', nargs='+')
parser.add_argument('-o', action='append', nargs='*')
args = parser.parse_args()

huangapple
  • 本文由 发表于 2023年3月7日 17:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定