pythonargparsemultiple-arguments

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


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
]

Solution

  • 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()