[New-bugs-announce] [issue9540] argparse: combine subparsers with global positional args

Michael.Elsdörfer report at bugs.python.org
Sun Aug 8 03:26:45 CEST 2010

New submission from Michael.Elsdörfer <michael at elsdoerfer.info>:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title="commands")
>>> subparser = subparsers.add_parser('make')
>>> parser.add_argument('jobs', nargs='*')
>>> parser.print_help()
usage: [-h] {make} ... [jobs [jobs ...]]

While the printed usage looks innocuous enough, argparser isn't actually able to parse this the way I expect: The positional argument never get's to handle any jobs given, as apparently everything after the command is handled by the subparser:

>>> parser.parse_args(['make', 'something'])
usage:  make [-h]
 make: error: unrecognized arguments: something

It seems that argparse, upon determining that the subparser can't handle a positional argument, could break out of the subparser, and let the parent parser continue. If necessary, as further help for argparse on how to resolve such situations, a parameter could be added to add_subparsers() which would allow the user to indicate that this group of subparsers should not support positional arguments.

The usage string should then print as:

>>> parser.print_help()
usage: [-h] {make} [jobs [jobs ...]]

That is, without the "..." after the command.

Finally, if it is decided that the feature will not be added, argparse should not allow the user to add positional arguments after a subparser.

components: Library (Lib)
messages: 113229
nosy: elsdoerfer
priority: normal
severity: normal
status: open
title: argparse: combine subparsers with global positional args
type: feature request
versions: Python 2.7, Python 3.1, Python 3.2, Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list