]> granicus.if.org Git - python/commitdiff
#22709: Use stdin as-is if it does not have a buffer attribute.
authorR David Murray <rdmurray@bitdance.com>
Sat, 2 Jan 2016 20:41:41 +0000 (15:41 -0500)
committerR David Murray <rdmurray@bitdance.com>
Sat, 2 Jan 2016 20:41:41 +0000 (15:41 -0500)
This restores backward compatibility lost in the fix for #21075, and
is better duck typing.

Patch by Akira Li.

Lib/fileinput.py
Lib/test/test_fileinput.py
Misc/NEWS

index c41b94abff72553d0ca0f0ced6c192f78f4bab07..021e39f83a370f5ae93eb9aaf4a30a7a685f92e3 100644 (file)
@@ -328,7 +328,7 @@ class FileInput:
             if self._filename == '-':
                 self._filename = '<stdin>'
                 if 'b' in self._mode:
-                    self._file = sys.stdin.buffer
+                    self._file = getattr(sys.stdin, 'buffer', sys.stdin)
                 else:
                     self._file = sys.stdin
                 self._isstdin = True
index 4765a056f6a4ffb029a66e3ea65fc30a89145d47..91c11668bd6dbeb296c4a1d0b46a04dfbbeeca16 100644 (file)
@@ -240,6 +240,17 @@ class FileInputTests(unittest.TestCase):
             lines = list(fi)
             self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
 
+    def test_detached_stdin_binary_mode(self):
+        orig_stdin = sys.stdin
+        try:
+            sys.stdin = BytesIO(b'spam, bacon, sausage, and spam')
+            self.assertFalse(hasattr(sys.stdin, 'buffer'))
+            fi = FileInput(files=['-'], mode='rb')
+            lines = list(fi)
+            self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
+        finally:
+            sys.stdin = orig_stdin
+
     def test_file_opening_hook(self):
         try:
             # cannot use openhook and inplace mode
index 6d242523823d7ae2ecbba82b97e845daf45afbf0..c5261304a3be68329f14eda789f37dcc11836c4d 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -41,6 +41,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #25447: fileinput now uses sys.stdin as-is if it does not have a
+  buffer attribute (restores backward compatibility).
+
 - Issue #25447: Copying the lru_cache() wrapper object now always works,
   independedly from the type of the wrapped object (by returning the original
   object unchanged).