Skip to content

bpo-41255: handle argparse errors with exit_on_error=False consistently #27295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2090,8 +2090,9 @@ Exiting methods

.. method:: ArgumentParser.error(message)

This method prints a usage message including the *message* to the
standard error and terminates the program with a status code of 2.
When exit on error is ``True`` this method prints a usage message including
the *message* to the standard error and terminates the program with a status
code of 2, otherwise raises an ArgumentError.


Intermixed parsing
Expand Down
18 changes: 10 additions & 8 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1872,13 +1872,11 @@ def parse_known_args(self, args=None, namespace=None):
setattr(namespace, dest, self._defaults[dest])

# parse the arguments and exit if there are any errors
if self.exit_on_error:
try:
namespace, args = self._parse_known_args(args, namespace)
except ArgumentError as err:
self.error(str(err))
else:
try:
namespace, args = self._parse_known_args(args, namespace)
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))

if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
Expand Down Expand Up @@ -2588,12 +2586,16 @@ def exit(self, status=0, message=None):
def error(self, message):
"""error(message: string)

Prints a usage message incorporating the message to stderr and
exits.
When exit_on_error is true prints a usage message
incorporating the message to stderr and exits, otherwise raises
an ArgumentError.

If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
if not self.exit_on_error:
raise ArgumentError(None, message)

self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
10 changes: 9 additions & 1 deletion Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5541,7 +5541,7 @@ class TestExitOnError(TestCase):

def setUp(self):
self.parser = argparse.ArgumentParser(exit_on_error=False)
self.parser.add_argument('--integers', metavar='N', type=int)
self.parser.add_argument('--integers', metavar='N', type=int, required=True)

def test_exit_on_error_with_good_args(self):
ns = self.parser.parse_args('--integers 4'.split())
Expand All @@ -5551,6 +5551,14 @@ 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_missing_required_args(self):
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args([])

def test_exit_on_error_unknown_args(self):
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args("--integers 1 --unknown-arg".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 @@
fixed errors with argparse exit_on_error causing unexpected behavior