在Python2中从sys.stdin制作io.BufferedReader [英] Making io.BufferedReader from sys.stdin in Python2
问题描述
如何从标准文件对象(例如sys.stdin或从 open中获得的文件)中创建BufferedReader对象?
How can I make a BufferedReader object from a standard file object, like sys.stdin or what you get from 'open'?
(背景:我需要一个peek()方法,这是标准文件对象无法使用的方法。也欢迎您解决此问题的任何建议。)
(Background: I need a peek() method, which the standard file objects fail at having. Any suggestions to solve this issue are also welcome.)
我希望这种方法能正常工作,但没有:
I'd have sort of expected this to work, but it doesn't:
>>> import sys
>>> import io
>>> io.BufferedReader(sys.stdin)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'readable'
(这是Python 2.7 )
(This is Python 2.7)
哈哈,至少对于有文件描述符的任何东西都可以。
Hah, got it, at least for anything that has a file descriptor.
stream = sys.stdin, or open(...), etc.
reader = io.open(stream.fileno(), mode='rb', closefd=False)
推荐答案
出于相同的原因,我也在寻找相同的代码(使用偷看)。这可行:
I was also looking for the same code for the same reason (using peek) awhile ago. And this works:
reader = io.open(sys.stdin.fileno())
这篇关于在Python2中从sys.stdin制作io.BufferedReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!