[issue9340] argparse parse_known_args does not work with subparsers
Steven Bethard
report at bugs.python.org
Fri Jul 23 14:00:05 CEST 2010
New submission from Steven Bethard <steven.bethard at gmail.com>:
[Moved from http://code.google.com/p/argparse/issues/detail?id=45]
If you try to use parse_known_args and you have a subparser, the subparser will still complain if it sees extra arguments:
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> subparsers.add_parser('A')
>>> parser.parse_known_args(['A', '--foo', 'b'])
usage: A [-h]
A: error: unrecognized arguments: --foo b
What should be returned is probably:
>>> parser.parse_known_args(['A', '--foo', 'b'])
(Namespace(), ['--foo', 'b'])
The problem is that subparsers don't know whether they're being called by parse_args() or parse_known_args(). I see a few possible fixes:
* Add another argument to Action.__call__ that indicates what method is being called. But that would break any existing subclasses.
* Do some stack inspection using sys._getframe(). But that's not guaranteed to work on other implementations of Python.
* When parse_args is called, set some flag on the subparsers object that causes it to call parse_known_args instead, and restore that flag before parse_known_args returns. This probably introduces potential threading issues, though practically perhaps they'll never turn up.
----------
assignee: bethard
components: Library (Lib)
messages: 111285
nosy: bethard
priority: normal
severity: normal
stage: needs patch
status: open
title: argparse parse_known_args does not work with subparsers
type: behavior
versions: Python 2.7, Python 3.2, Python 3.3
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9340>
_______________________________________
More information about the Python-bugs-list
mailing list