passing an argument as list using argparse but facing issues

Question:

I am trying to pass a list of values as arguments using this code:

parser.add_argument('--items', nargs='+', help='items to buy')

and using this to pass the items:

--items=bread milk

from debugging I see that it is making a list of one index and that has ‘bread milk’ into to
while I was hoping it would make a list of two items like [‘bread’,’milk’].
how can I fix it?

I saw some a lot of people mentioning this code to make it happen:

parser.add_argument('-l', '--l', nargs='+', help='list = [title, HTML]')

but when I use the same line of code, just changing "l" to "items", it doesnt work.

Asked By: qabootar

||

Answers:

Check this out:

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--items", nargs='+', help="items to buy")
args = ap.parse_args()
items = args.items

print(items)

Test:

python3 test.py -i bread milk eggs butter

Output:

['bread', 'milk', 'eggs', 'butter']
Answered By: Shivika P