Skip to content

gh-101640: Make argparse working in pythonw by dropping stderr writes there #101802

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

Merged
merged 5 commits into from
May 6, 2023
Merged
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
8 changes: 5 additions & 3 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2605,9 +2605,11 @@ def print_help(self, file=None):

def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
file = file or _sys.stderr
try:
file.write(message)
except (AttributeError, OSError):
pass

# ===============
# Exiting methods
Expand Down
31 changes: 31 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Author: Steven J. Bethard <[email protected]>.

import contextlib
import functools
import inspect
import io
import operator
Expand Down Expand Up @@ -35,6 +37,35 @@ def getvalue(self):
return self.buffer.raw.getvalue().decode('utf-8')


class StdStreamTest(unittest.TestCase):

def test_skip_invalid_stderr(self):
parser = argparse.ArgumentParser()
with (
contextlib.redirect_stderr(None),
mock.patch('argparse._sys.exit')
):
parser.exit(status=0, message='foo')

def test_skip_invalid_stdout(self):
parser = argparse.ArgumentParser()
for func in (
parser.print_usage,
parser.print_help,
functools.partial(parser.parse_args, ['-h'])
):
with (
self.subTest(func=func),
contextlib.redirect_stdout(None),
# argparse uses stderr as a fallback
StdIOBuffer() as mocked_stderr,
contextlib.redirect_stderr(mocked_stderr),
mock.patch('argparse._sys.exit'),
):
func()
self.assertRegex(mocked_stderr.getvalue(), r'usage:')


class TestCase(unittest.TestCase):

def setUp(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`argparse.ArgumentParser` now catches errors when writing messages, such as when :data:`sys.stderr` is ``None``. Patch by Oleg Iarygin.