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

2024-05-14 23:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 对象方法ioimport内容streamstdinsys

热门问题