i need to use argparse to accept a variable number of strings from command line, but when i pass zero arguments i get a string as result instead of a list of one string.
argparser = argparse.ArgumentParser()
argparser.add_argument(
    '--example',
    nargs='*',
    default='default_value',
    type=str)
args = argparser.parse_args()
for e in args.example:
    print(e)
When executing this python program --example first_arg second_arg i get the expected result:
first_arg
second_arg
Even with one argument everything is fine, but executing this python program i get:
d
e
f
a
u
l
t
_
v
a
l
u
e
I'd need to iterate over the list without considering how many elements it has, how could i solve this? Thank you in advance.
Set the default to a list instead of a string:
argparser.add_argument(
    '--example',
    nargs='*',
    default=['default_value'],
    type=str)
Your default value is a str which can be iterated in python, you can change the default to a list like this:
argparser.add_argument(
    '--example',
    nargs='*',
    default=['default_value'],
    type=str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With