Skip to content

Commit

Permalink
[3.13] pythongh-121018: Ensure ArgumentParser.parse_args with exit_on…
Browse files Browse the repository at this point in the history
…_error=False raises instead of exiting when given unrecognized arguments (pythonGH-121019) (pythonGH-121032)

(cherry picked from commit 0654336)

Co-authored-by: blhsing <blhsing@gmail.com>
  • Loading branch information
miss-islington and blhsing authored Jun 26, 2024
1 parent f2b4f51 commit 6bc7e2c
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
6 changes: 4 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1871,8 +1871,10 @@ def _get_positional_actions(self):
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):
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -6096,6 +6096,9 @@ def test_exit_on_error_with_bad_args(self):
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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 6bc7e2c

Please sign in to comment.