New submission from Steven Bethard <[email protected]>:
[From the old argparse tracker:
http://code.google.com/p/argparse/issues/detail?id=20]
You can't follow a nargs='+' optional argument with a positional argument:
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--badger', nargs='+')
>>> parser.add_argument('spam')
>>> parser.parse_args('--badger A B C D'.split())
usage: PROG [-h] [--badger BADGER [BADGER ...]] spam
PROG: error: too few arguments
Ideally, this should produce:
>>> parser.parse_args('--badger A B C D'.split())
Namespace(badger=['A', 'B', 'C'], spam='D')
The problem is that the nargs='+' causes the optional to consume all the
arguments following it, even though we should know that we need to save one for
the final positional argument.
A workaround is to specify '--', e.g.:
>>> parser.parse_args('--badger A B C -- D'.split())
Namespace(badger=['A', 'B', 'C'], spam='D')
The problem arises from the fact that argparse uses regular-expression style
matching for positional arguments, but it does that separately from what it
does for optional arguments.
One solution might be to build a regular expression of the possible things a
parser could match. So given a parser like::
parser = argparse.ArgumentParser()
parser.add_argument('-w')
parser.add_argument('-x', nargs='+')
parser.add_argument('y')
parser.add_argument('z', nargs='*')
the regular expression might look something like (where positionals have been
replaced by the character A)::
(-w A)? (-x A+)? A (-w A)? (-x A+)? A* (-w A)? (-x A+)?
Note that the optionals can appear between any positionals, so I have to repeat
their regular expressions multiple times. Because of this, I worry about how
big the regular expression might grow to be for large parsers. But maybe this
is the right way to solve the problem.
----------
messages: 111270
nosy: bethard
priority: normal
severity: normal
stage: needs patch
status: open
title: argparse optionals with nargs='+' can't be followed by positionals
type: feature request
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue9338>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com