英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论