Argparse option for passing a list as option

1.7K    Asked by YajairaSatchell in Data Science , Asked on Jun 8, 2021

I am trying to pass a list as an argument to a command-line program. Is there an argparse option to pass a list as option? 


parser.add_argument('-l', '--list',
type=list, action='store',
dest='list',
help=' Set flag',
required=True)

The script is called like below

python test.py -l "265340 268738 270774 270817"


Answered by Hellen Cargill

There are many ways to pass a list as an argument to a command-line program some of the important methods are as follows:-

You can pass a delimited string. The reason to pass delimited string is as follows:-

Because the list can be of any type int or str, and sometimes using nargs is good if there are multiple optional arguments and positional arguments. Below is the code that shows how to use the delimited string:-

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item)for item in args.list.split(',')]
You can call the script as follows:-
python test.py -l "265340,268738,270774,270817" [other arguments]

OR

    python test.py -l 265340,268738,270774,270817 [other arguments]

Both will work fine and the delimiter can be space too, which would though enforce quotes around the argument value like in the example in the question.

What is the python argparse list?

argparse is the “recommended command-line parsing module in the Python standard library. Using a list as an argparse argument passes any number of values to a flag in Python. This assigns a list of values to a flag that is used when executing the Python program from the command line.



Your Answer

Interviews

Parent Categories