在Python2中从sys.stdin创建io.BufferedReader

时间:2011-05-19 21:39:27

标签: python bufferedreader python-2.x

如何从标准文件对象中创建BufferedReader对象,例如sys.stdin或从“open”获得的内容?

(背景:我需要一个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'

(这是Python 2.7)

哈,得到它,至少对于任何有文件描述符的东西。

stream = sys.stdin, or open(...), etc.
reader = io.open(stream.fileno(), mode='rb', closefd=False)

1 个答案:

答案 0 :(得分:13)

前一段时间我也在寻找同样的代码(使用peek)。这有效:

reader = io.open(sys.stdin.fileno())