Skip to content

Commit 830207e

Browse files
committed
python#22709: Use stdin as-is if it does not have a buffer attribute.
This restores backward compatibility lost in the fix for python#21075, and is better duck typing. Patch by Akira Li.
1 parent fcb6db5 commit 830207e

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/fileinput.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ def readline(self):
328328
if self._filename == '-':
329329
self._filename = '<stdin>'
330330
if 'b' in self._mode:
331-
self._file = sys.stdin.buffer
331+
self._file = getattr(sys.stdin, 'buffer', sys.stdin)
332332
else:
333333
self._file = sys.stdin
334334
self._isstdin = True

Lib/test/test_fileinput.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,17 @@ def test_stdin_binary_mode(self):
240240
lines = list(fi)
241241
self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
242242

243+
def test_detached_stdin_binary_mode(self):
244+
orig_stdin = sys.stdin
245+
try:
246+
sys.stdin = BytesIO(b'spam, bacon, sausage, and spam')
247+
self.assertFalse(hasattr(sys.stdin, 'buffer'))
248+
fi = FileInput(files=['-'], mode='rb')
249+
lines = list(fi)
250+
self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
251+
finally:
252+
sys.stdin = orig_stdin
253+
243254
def test_file_opening_hook(self):
244255
try:
245256
# cannot use openhook and inplace mode

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ Core and Builtins
4141
Library
4242
-------
4343

44+
- Issue #25447: fileinput now uses sys.stdin as-is if it does not have a
45+
buffer attribute (restores backward compatibility).
46+
4447
- Issue #25447: Copying the lru_cache() wrapper object now always works,
4548
independedly from the type of the wrapped object (by returning the original
4649
object unchanged).

0 commit comments

Comments
 (0)