4
votes

So I am trying to create a parser which can take an arbitrary list of choices (things to plot), with optional parameters specified for each choice. And have eschewed the idea of sub-subparsers for just using multiple arguments of the form:

--plot foo --xlim 0 10 --ylim -5 5 --plot bar --xlim -5 5 --ylim 0 10 --clim 1e24 1e27

But I can't seem to get an append action to work with nargs=2:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append', nargs=2, type=int)
_AppendAction(option_strings=['--foo'], dest='foo', nargs=2, const=None, default=None,  type=<type 'int'>, choices=None, help=None, metavar=None)
>>> parser.parse_args("--foo 1 2 --foo 3 4")
usage: [-h] [--foo FOO FOO]
: error: unrecognized arguments: - - f o o   1   2   - - f o o   3 4

I was hoping that I would get a list of lists or a list of tuples. Is is my desired behaviour unsupported by argparse or am I just doing something wrong in my implementation?

1
Didn't you notice how parse_args is called in the examples? They always use parse_args('--foo 1 2'.split()). Note the final .split() that turns a string into a list of strings. - Bakuriu

1 Answers

4
votes

You should pass a list of strings, not a string:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append', nargs=2, type=int)
_AppendAction(option_strings=['--foo'], dest='foo', nargs=2, const=None, default=None, type=<type 'int'>, choices=None, help=None, metavar=None)
>>> parser.parse_args(["--foo", "1", "2", "--foo", "3", "4"])  # <----
Namespace(foo=[[1, 2], [3, 4]])