Question

I am new to Python and I would like to implement a script.py so to handle the following command

python script.py --opt value1 --opt value2 --opt value3 ... --opt valueN

and to print all --opt values, like this:

value1
value2
value3
...
valueN

How can I make that?


My script is:

parser = argparse.ArgumentParser()
parser.add_argument("--opt", help="option description")
args = parser.parse_args()

for arg_opt in args.opt:
    print(arg_opt)

I tried to play with the for loop to iterate over the --opt value but without success: running the above code will output just the last --opt value.

Was it helpful?

Solution

Set the action argument to append:

'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--opt", action='append')

args = parser.parse_args()
print(args.opt)

Demo:

$ python test_argparse.py --opt value1 --opt value2 --opt value3
['value1', 'value2', 'value3']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top