diff --git a/Lib/fileinput.py b/Lib/fileinput.py index c41b94abff7..021e39f83a3 100644 --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -328,7 +328,7 @@ def readline(self): if self._filename == '-': self._filename = '' 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 diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index 4765a056f6a..91c11668bd6 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -240,6 +240,17 @@ def test_stdin_binary_mode(self): 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 diff --git a/Misc/NEWS b/Misc/NEWS index 6d242523823..c5261304a3b 100644 --- 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).