如何从标准文件对象(如sys.stdin或从“open”获得的内容)创建BufferedReader对象?
(背景:我需要一个peek()方法,标准文件对象不能拥有它。我们也欢迎提出任何解决这个问题的建议。)
我本以为这会起作用,但它没有:
>>> 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'
(这是Python2.7)
哈,明白了,至少对于任何有文件描述符的东西。
stream = sys.stdin, or open(...), etc.
reader = io.open(stream.fileno(), mode='rb', closefd=False)
不久前,我也出于同样的原因(使用peek)寻找相同的代码。这是有效的:
相关问题 更多 >
编程相关推荐