]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-121018: Ensure ArgumentParser.parse_args with exit_on_error=False raises instead...
authorblhsing <blhsing@gmail.com>
Wed, 26 Jun 2024 07:41:51 +0000 (15:41 +0800)
committerGitHub <noreply@github.com>
Wed, 26 Jun 2024 07:41:51 +0000 (10:41 +0300)
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 cdd29d3ad568e5592fe0d516260388506d1184eb..f1c3808869aab3af3ad416513e15399725afd9c2 100644 (file)
@@ -1843,8 +1843,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 eb1a9f5146beb4f7b8577ae39c9e56cafc8f7526..11eb081f45701eb6359dcb83b2d035d3d01f9d7f 100644 (file)
@@ -6053,6 +6053,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..f311077
--- /dev/null
@@ -0,0 +1,2 @@
+Fixed an issue where :func:`argparse.ArgumentParser.parses_args` did not honor ``exit_on_error=False`` when given unrecognized arguments.\r
+Patch by Ben Hsing