Skip to content
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
15 changes: 15 additions & 0 deletions Lib/test/test_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1512,6 +1512,21 @@ def test_asyncgen_hooks(self):
self.assertIsNone(cur.firstiter)
self.assertIsNone(cur.finalizer)

def test_changing_sys_stderr_and_removing_reference(self):
# If the default displayhook doesn't take a strong reference
# to sys.stderr the following code can crash. See bpo-43660
# for more details.
code = textwrap.dedent('''
import sys
class MyStderr:
def write(self, s):
sys.stderr = None
sys.stderr = MyStderr()
1/0
''')
rc, out, err = assert_python_failure('-c', code)
self.assertEqual(out, b"")
self.assertEqual(err, b"")

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix crash that happens when replacing ``sys.stderr`` with a callable that
can remove the object while an exception is being printed. Patch by Pablo
Galindo.
3 changes: 2 additions & 1 deletion Python/pythonrun.c
Original file line number Diff line number Diff line change
Expand Up @@ -1082,8 +1082,9 @@ PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
if (file == Py_None) {
return;
}

Py_INCREF(file);
_PyErr_Display(file, exception, value, tb);
Py_DECREF(file);
}

PyObject *
Expand Down