Skip to content

Commit 6bc7e2c

Browse files
[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 0654336) Co-authored-by: blhsing <[email protected]>
1 parent f2b4f51 commit 6bc7e2c

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

Lib/argparse.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1871,8 +1871,10 @@ def _get_positional_actions(self):
18711871
def parse_args(self, args=None, namespace=None):
18721872
args, argv = self.parse_known_args(args, namespace)
18731873
if argv:
1874-
msg = _('unrecognized arguments: %s')
1875-
self.error(msg % ' '.join(argv))
1874+
msg = _('unrecognized arguments: %s') % ' '.join(argv)
1875+
if self.exit_on_error:
1876+
self.error(msg)
1877+
raise ArgumentError(None, msg)
18761878
return args
18771879

18781880
def parse_known_args(self, args=None, namespace=None):

Lib/test/test_argparse.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6096,6 +6096,9 @@ def test_exit_on_error_with_bad_args(self):
60966096
with self.assertRaises(argparse.ArgumentError):
60976097
self.parser.parse_args('--integers a'.split())
60986098

6099+
def test_exit_on_error_with_unrecognized_args(self):
6100+
with self.assertRaises(argparse.ArgumentError):
6101+
self.parser.parse_args('--foo bar'.split())
60996102

61006103
def tearDownModule():
61016104
# Remove global references to avoid looking like we have refleaks.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed an issue where :meth:`!argparse.ArgumentParser.parses_args` did not honor ``exit_on_error=False`` when given unrecognized arguments.
2+
Patch by Ben Hsing.

0 commit comments

Comments
 (0)