在Python2中从sys.stdin生成io.BufferedReader

在Python2中从sys.stdin生成io.BufferedReader,python,bufferedreader,python-2.x,Python,Bufferedreader,Python 2.x,如何从标准文件对象(如sys.stdin或从“open”获得的内容)生成BufferedReader对象 (背景:我需要一个peek()方法,标准文件对象无法使用它。也欢迎提出任何解决此问题的建议。) 我有点期待它会起作用,但它没有: >>> import sys >>> import io >>> io.BufferedReader(sys.stdin) Traceback (most recent call last): File

如何从标准文件对象(如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'

不久前,出于同样的原因(使用peek),我也在寻找相同的代码。这是有效的:

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

什么是
peek()
方法?您到底想要什么?peek()返回流中的下一项,而不将其从流中删除。我正在写一个语法分析器,希望有前瞻性。您使用的是哪些没有文件描述符的输入源?
reader = io.open(sys.stdin.fileno())