diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py index 47763219f83..9ac2139e330 100644 --- a/Lib/test/test_warnings.py +++ b/Lib/test/test_warnings.py @@ -666,6 +666,15 @@ class _WarningsTests(BaseTest, unittest.TestCase): finally: globals_dict['__file__'] = oldfile + def test_stderr_none(self): + rc, stdout, stderr = assert_python_ok("-c", + "import sys; sys.stderr = None; " + "import warnings; warnings.simplefilter('always'); " + "warnings.warn('Warning!')") + self.assertEqual(stdout, b'') + self.assertNotIn(b'Warning!', stderr) + self.assertNotIn(b'Error', stderr) + class WarningsDisplayTests(BaseTest): diff --git a/Lib/warnings.py b/Lib/warnings.py index f7319258f8e..8ca0f730cb1 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -11,6 +11,9 @@ def showwarning(message, category, filename, lineno, file=None, line=None): """Hook to write a warning to a file; replace if you like.""" if file is None: file = sys.stderr + if file is None: + # sys.stderr is None when ran with pythonw.exe - warnings get lost + return try: file.write(formatwarning(message, category, filename, lineno, line)) except OSError: diff --git a/Misc/NEWS b/Misc/NEWS index 8587874b685..36689c0ed2b 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -194,6 +194,9 @@ Core and Builtins Library ------- +- Issue #23016: A warning no longer produces an AttributeError when the program + is run with pythonw.exe. + - Issue #21775: shutil.copytree(): fix crash when copying to VFAT. An exception handler assumed that that OSError objects always have a 'winerror' attribute. That is not the case, so the exception handler itself raised AttributeError