[issue9253] argparse: optional subparsers
paul j3
report at bugs.python.org
Tue Apr 9 09:08:43 CEST 2013
paul j3 added the comment:
I think this problem arises from a change made in http://bugs.python.org/issue10424
Changeset to default (i.e. development) is
http://hg.python.org/cpython/rev/cab204a79e09
Near the end of _parse_known_args it removes a:
if positionals:
self.error(_('too few arguments'))
with a scan for required options that have not been seen.
Ordinary positionals are required. But a SubParsersAction is not required. So we no longer get a warning.
http://bugs.python.org/issue12776 changed this block of code as well. Notice the 2.7 and 3.2 branches have this 'too few arguments' error, but the default does not.
The default value for Action.required is False. In _get_positional_kwargs(), a positional's required is set based on nargs (e.g. '+' is required, '*' not). But add_subparsers() does not use this, so its 'required' ends up False.
This fudge seems to do the trick:
parser = ArgumentParser(prog='test')
subparsers = parser.add_subparsers()
subparsers.required = True
subparsers.dest = 'command'
subparser = subparsers.add_parser("foo", help="run foo")
parser.parse_args()
producing an error message:
usage: test [-h] {foo} ...
test: error: the following arguments are required: command
subparsers.dest is set so the error message can give this positional a name.
I'll try to write a patch to do something similar in argparse itself.
----------
nosy: +paul.j3
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9253>
_______________________________________
More information about the Python-bugs-list
mailing list