]> granicus.if.org Git - python/commitdiff
#14161: fix the __repr__ of file objects to escape the file name.
authorEzio Melotti <ezio.melotti@gmail.com>
Sun, 11 Mar 2012 23:17:02 +0000 (01:17 +0200)
committerEzio Melotti <ezio.melotti@gmail.com>
Sun, 11 Mar 2012 23:17:02 +0000 (01:17 +0200)
Lib/test/test_file2k.py
Misc/NEWS
Objects/fileobject.c

index 399f119b81b870438f8856eb458ab051359d2e48..0c892bd2baf8fb66d5401a7f2c719ed43615a0ee 100644 (file)
@@ -89,6 +89,13 @@ class AutoFileTests(unittest.TestCase):
     def testRepr(self):
         # verify repr works
         self.assertTrue(repr(self.f).startswith("<open file '" + TESTFN))
+        # see issue #14161
+        # Windows doesn't like \r\n\t" in the file name, but ' is ok
+        fname = 'xx\rxx\nxx\'xx"xx' if sys.platform != "win32" else "xx'xx"
+        with open(fname, 'w') as f:
+            self.addCleanup(os.remove, fname)
+            self.assertTrue(repr(f).startswith(
+                    "<open file %r, mode 'w' at" % fname))
 
     def testErrors(self):
         self.f.close()
index c5c2c8225a6f099b027645d67425a87e33ea3354..6ef8376a9c46e9eebce978d9260b73fc14b36740 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -9,6 +9,8 @@ What's New in Python 2.7.4
 Core and Builtins
 -----------------
 
+- Issue #14161: fix the __repr__ of file objects to escape the file name.
+
 - Issue #1469629: Allow cycles through an object's __dict__ slot to be
   collected. (For example if ``x.__dict__ is x``).
 
index 737ebb76350e521df9b5b4b51a723a4c825a5f08..79b9aad4e8943c8fae326456f75a64c563875d3b 100644 (file)
@@ -635,10 +635,11 @@ file_dealloc(PyFileObject *f)
 static PyObject *
 file_repr(PyFileObject *f)
 {
+    PyObject *ret = NULL;
+    PyObject *name = NULL;
     if (PyUnicode_Check(f->f_name)) {
 #ifdef Py_USING_UNICODE
-        PyObject *ret = NULL;
-        PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
+        name = PyUnicode_AsUnicodeEscapeString(f->f_name);
         const char *name_str = name ? PyString_AsString(name) : "?";
         ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
                            f->f_fp == NULL ? "closed" : "open",
@@ -649,11 +650,16 @@ file_repr(PyFileObject *f)
         return ret;
 #endif
     } else {
-        return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
+        name = PyObject_Repr(f->f_name);
+        if (name == NULL)
+            return NULL;
+        ret = PyString_FromFormat("<%s file %s, mode '%s' at %p>",
                            f->f_fp == NULL ? "closed" : "open",
-                           PyString_AsString(f->f_name),
+                           PyString_AsString(name),
                            PyString_AsString(f->f_mode),
                            f);
+        Py_XDECREF(name);
+        return ret;
     }
 }