Skip to content

Commit ba7f863

Browse files
bpo-43660: Fix crash when displaying exceptions with custom values for sys.stderr (GH-25075)
(cherry picked from commit 09b90a0) Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
1 parent 20b2f2b commit ba7f863

3 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎Lib/test/test_sys.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1441,6 +1441,21 @@ def test_asyncgen_hooks(self):
14411441
self.assertIsNone(cur.firstiter)
14421442
self.assertIsNone(cur.finalizer)
14431443

1444+
def test_changing_sys_stderr_and_removing_reference(self):
1445+
# If the default displayhook doesn't take a strong reference
1446+
# to sys.stderr the following code can crash. See bpo-43660
1447+
# for more details.
1448+
code = textwrap.dedent('''
1449+
import sys
1450+
class MyStderr:
1451+
def write(self, s):
1452+
sys.stderr = None
1453+
sys.stderr = MyStderr()
1454+
1/0
1455+
''')
1456+
rc, out, err = assert_python_failure('-c', code)
1457+
self.assertEqual(out, b"")
1458+
self.assertEqual(err, b"")
14441459

14451460
if __name__ == "__main__":
14461461
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix crash that happens when replacing ``sys.stderr`` with a callable that
2+
can remove the object while an exception is being printed. Patch by Pablo
3+
Galindo.

‎Python/pythonrun.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1034,8 +1034,9 @@ PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
10341034
if (file == Py_None) {
10351035
return;
10361036
}
1037-
1037+
Py_INCREF(file);
10381038
_PyErr_Display(file, exception, value, tb);
1039+
Py_DECREF(file);
10391040
}
10401041

10411042
PyObject *

0 commit comments

Comments
 (0)