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

nargs='+' does not work as 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 using --name foo bar , but unlike the other tools I used, and I would rather be more explicit. Does this argparse ?

+6
source share
1 answer

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 used if you just want to take a series of positional arguments, and action='append' works if you want to have the flag more than once and accumulate the results in the list.

+7
source

Source: https://habr.com/ru/post/988925/


All Articles