mirror of
https://github.com/python/cpython.git
synced 2025-08-03 08:34:29 +00:00
[3.13] gh-121018: Ensure ArgumentParser.parse_args with exit_on_error=False raises instead of exiting when given unrecognized arguments (GH-121019) (GH-121032)
(cherry picked from commit 0654336dd5
)
Co-authored-by: blhsing <blhsing@gmail.com>
This commit is contained in:
parent
f2b4f517b9
commit
6bc7e2cca5
3 changed files with 9 additions and 2 deletions
|
@ -1871,8 +1871,10 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
|
||||||
def parse_args(self, args=None, namespace=None):
|
def parse_args(self, args=None, namespace=None):
|
||||||
args, argv = self.parse_known_args(args, namespace)
|
args, argv = self.parse_known_args(args, namespace)
|
||||||
if argv:
|
if argv:
|
||||||
msg = _('unrecognized arguments: %s')
|
msg = _('unrecognized arguments: %s') % ' '.join(argv)
|
||||||
self.error(msg % ' '.join(argv))
|
if self.exit_on_error:
|
||||||
|
self.error(msg)
|
||||||
|
raise ArgumentError(None, msg)
|
||||||
return args
|
return args
|
||||||
|
|
||||||
def parse_known_args(self, args=None, namespace=None):
|
def parse_known_args(self, args=None, namespace=None):
|
||||||
|
|
|
@ -6096,6 +6096,9 @@ class TestExitOnError(TestCase):
|
||||||
with self.assertRaises(argparse.ArgumentError):
|
with self.assertRaises(argparse.ArgumentError):
|
||||||
self.parser.parse_args('--integers a'.split())
|
self.parser.parse_args('--integers a'.split())
|
||||||
|
|
||||||
|
def test_exit_on_error_with_unrecognized_args(self):
|
||||||
|
with self.assertRaises(argparse.ArgumentError):
|
||||||
|
self.parser.parse_args('--foo bar'.split())
|
||||||
|
|
||||||
def tearDownModule():
|
def tearDownModule():
|
||||||
# Remove global references to avoid looking like we have refleaks.
|
# Remove global references to avoid looking like we have refleaks.
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
Fixed an issue where :meth:`!argparse.ArgumentParser.parses_args` did not honor ``exit_on_error=False`` when given unrecognized arguments.
|
||||||
|
Patch by Ben Hsing.
|
Loading…
Add table
Add a link
Reference in a new issue