Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
l0b0 Avatar asked Jun 11 '15 12:06

l0b0


People also ask

How do I add Argparse optional arguments?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .

What does DEST do in Argparse?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object. dest identifies an argument.


1 Answers

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.

like image 52
Brian Campbell Avatar answered Oct 06 '22 13:10

Brian Campbell