]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-121018: Ensure ArgumentParser.parse_args with exit_on_error=False raises...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 26 Jun 2024 10:16:44 +0000 (12:16 +0200)
committerGitHub <noreply@github.com>
Wed, 26 Jun 2024 10:16:44 +0000 (10:16 +0000)
(cherry picked from commit 0654336dd5138aec04e3017e15ccbb90a44e053d)

Co-authored-by: blhsing <blhsing@gmail.com>
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-06-26-03-04-24.gh-issue-121018.clVSc4.rst [new file with mode: 0644]

index 120cb6c845897f54973cd57e8f61e38ce646beac..0890718270f46e62a59788b5bf3008a980dedaa3 100644 (file)
@@ -1895,8 +1895,10 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
     def parse_args(self, args=None, namespace=None):
         args, argv = self.parse_known_args(args, namespace)
         if argv:
-            msg = _('unrecognized arguments: %s')
-            self.error(msg % ' '.join(argv))
+            msg = _('unrecognized arguments: %s') % ' '.join(argv)
+            if self.exit_on_error:
+                self.error(msg)
+            raise ArgumentError(None, msg)
         return args
 
     def parse_known_args(self, args=None, namespace=None):
index 940c93bcb02a3b45b82cd6f27fbe645abf280be5..a4d6c4a35256f9f623f80fad8f6107da089d6db6 100644 (file)
@@ -5743,6 +5743,9 @@ class TestExitOnError(TestCase):
         with self.assertRaises(argparse.ArgumentError):
             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():
     # Remove global references to avoid looking like we have refleaks.
diff --git a/Misc/NEWS.d/next/Library/2024-06-26-03-04-24.gh-issue-121018.clVSc4.rst b/Misc/NEWS.d/next/Library/2024-06-26-03-04-24.gh-issue-121018.clVSc4.rst
new file mode 100644 (file)
index 0000000..fdc3c5f
--- /dev/null
@@ -0,0 +1,2 @@
+Fixed an issue where :meth:`!argparse.ArgumentParser.parses_args` did not honor ``exit_on_error=False`` when given unrecognized arguments.\r
+Patch by Ben Hsing.\r