Skip to content

Commit 946cfc3

Browse files
Issue python#21075: fileinput.FileInput now reads bytes from standard stream if
binary mode is specified. Patch by Sam Kimbrel.
1 parent e2d6690 commit 946cfc3

File tree

4 files changed

+17
-2
lines changed

4 files changed

+17
-2
lines changed

Lib/fileinput.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,10 @@ def readline(self):
320320
self._backupfilename = 0
321321
if self._filename == '-':
322322
self._filename = '<stdin>'
323-
self._file = sys.stdin
323+
if 'b' in self._mode:
324+
self._file = sys.stdin.buffer
325+
else:
326+
self._file = sys.stdin
324327
self._isstdin = True
325328
else:
326329
if self._inplace:

Lib/test/test_fileinput.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@
1919
except ImportError:
2020
gzip = None
2121

22-
from io import StringIO
22+
from io import BytesIO, StringIO
2323
from fileinput import FileInput, hook_encoded
2424

2525
from test.support import verbose, TESTFN, run_unittest, check_warnings
2626
from test.support import unlink as safe_unlink
27+
from unittest import mock
2728

2829

2930
# The fileinput module has 2 interfaces: the FileInput class which does
@@ -232,6 +233,13 @@ def test_opening_mode(self):
232233
finally:
233234
remove_tempfiles(t1)
234235

236+
def test_stdin_binary_mode(self):
237+
with mock.patch('sys.stdin') as m_stdin:
238+
m_stdin.buffer = BytesIO(b'spam, bacon, sausage, and spam')
239+
fi = FileInput(files=['-'], mode='rb')
240+
lines = list(fi)
241+
self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
242+
235243
def test_file_opening_hook(self):
236244
try:
237245
# cannot use openhook and inplace mode

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,7 @@ Mads Kiilerich
674674
Jason Killen
675675
Jan Kim
676676
Taek Joo Kim
677+
Sam Kimbrel
677678
W. Trevor King
678679
Paul Kippes
679680
Steve Kirsch

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ Core and Builtins
2323
Library
2424
-------
2525

26+
- Issue #21075: fileinput.FileInput now reads bytes from standard stream if
27+
binary mode is specified. Patch by Sam Kimbrel.
28+
2629
- Issue #21396: Fix TextIOWrapper(..., write_through=True) to not force a
2730
flush() on the underlying binary stream. Patch by akira.
2831

0 commit comments

Comments
 (0)