diff Python/pythonrun.c @ 73762:37300a1df7d7

Issue #13444: When stdout has been closed explicitly, we should not attempt to flush it at shutdown and print an error. This also adds a test for issue #5319, whose resolution introduced the issue.
author Antoine Pitrou <solipsis@pitrou.net>
date Sat, 26 Nov 2011 22:02:29 +0100
parents c4c1c8af0115 150e096095e5
children c86fb10eaf68
line wrap: on
line diff
--- a/Python/pythonrun.c	Sat Nov 26 11:39:49 2011 -0600
+++ b/Python/pythonrun.c	Sat Nov 26 22:02:29 2011 +0100
@@ -348,6 +348,22 @@
 
 /* Flush stdout and stderr */
 
+static int
+file_is_closed(PyObject *fobj)
+{
+    int r;
+    PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
+    if (tmp == NULL) {
+        PyErr_Clear();
+        return 0;
+    }
+    r = PyObject_IsTrue(tmp);
+    Py_DECREF(tmp);
+    if (r < 0)
+        PyErr_Clear();
+    return r > 0;
+}
+
 static void
 flush_std_files(void)
 {
@@ -356,7 +372,7 @@
     PyObject *tmp;
     _Py_IDENTIFIER(flush);
 
-    if (fout != NULL && fout != Py_None) {
+    if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
         tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
         if (tmp == NULL)
             PyErr_WriteUnraisable(fout);
@@ -364,7 +380,7 @@
             Py_DECREF(tmp);
     }
 
-    if (ferr != NULL && ferr != Py_None) {
+    if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
         tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
         if (tmp == NULL)
             PyErr_Clear();