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

22 投票
1 回答
7284 浏览
提问于 2025-04-16 18:00

我怎么才能从一个标准文件对象,比如 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'

(这是 Python 2.7 的内容)

哈哈,终于搞定了,至少对于任何有文件描述符的东西来说。

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

1 个回答

14

我之前也因为同样的原因(使用 .peek())在找这个代码。这个方法可以用:

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

撰写回答