【发布时间】:2017-09-12 08:12:10
【问题描述】:
我在 Ubuntu 上使用 Python3.5。以下脚本创建了一个文件out,并用越来越多的“Hello”行填充它:
import contextlib
with contextlib.redirect_stdout(open('out','w')):
while True:
print('Hello')
但是,如果我通过添加对time.sleep() 的调用进行微小修改,则文件out 保持为空:
import contextlib
import time
with contextlib.redirect_stdout(open('out','w')):
while True:
print('Hello')
time.sleep(1)
如果我通过将循环变为有限循环来进一步更改代码,它会填充out,但只会在循环结束时一次性填充。
谁能重现并解释一下?
【问题讨论】:
标签: python io-redirection buffering