l0b0
l0b0

Reputation: 58788

How to use `--foo 1 --foo 2` style arguments with Python argparse?

nargs='+' doesn't work the way I expected:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--name", dest='names', nargs='+')
_StoreAction(option_strings=['--name'], dest='names', nargs='+', const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--name foo --name bar'.split())
Namespace(names=['bar'])

I can "fix" this by using --name foo bar, but that's unlike other tools I've used, and I'd rather be more explicit. Does argparse support this?

Upvotes: 6

Views: 127

Answers (1)

Brian Campbell
Brian Campbell

Reputation: 332776

You want to use action='append' instead of nargs='+':

>>> parser.add_argument("--name", dest='names', action='append')
_AppendAction(option_strings=['--name'], dest='names', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--name foo --name bar'.split())
Namespace(names=['foo', 'bar'])

nargs is used if you just want to take a series of positional arguments, while action='append' works if you want to be able to take a flag more than once and accumulate the results in a list.

Upvotes: 7

Related Questions