在Python2中从sys.stdin制作io.BufferedReader
如何从标准文件对象(例如 sys.stdin 或从“打开”中获得的内容)创建 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)
How can I make a BufferedReader object from a standard file object, like sys.stdin or what you get from 'open'?
(Background: I need a peek() method, which the standard file objects fail at having. Any suggestions to solve this issue are also welcome.)
I'd have sort of expected this to work, but it doesn't:
>>> 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'
(This is Python 2.7)
Hah, got it, at least for anything that has a file descriptor.
stream = sys.stdin, or open(...), etc.
reader = io.open(stream.fileno(), mode='rb', closefd=False)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不久前,我也出于同样的原因(使用
.peek()
)寻找相同的代码。这有效:I was also looking for the same code for the same reason (using
.peek()
) a while ago. And this works: