在我的 python 代码中有:
print "Hello"
time.sleep(20)
print "world"
我期待输出为
Hello
然后在 20 秒后
world
但是 Hello
和 world
正在控制台中同时打印。
最佳答案
print
运算符有效地将 sys.stdout
流用于缓冲的输出。
对于实时输出,您需要使用未缓冲的 sys.stderr
流:
import sys, time
sys.stderr.write("Hello ")
time.sleep(20)
sys.stderr.write("world\n")
或者,您可以在每次需要输出时通过调用 sys.stdout.flush()
手动刷新流缓冲区,但我建议您不要以这种方式进行,除非您知道自己在做什么正在做。
有关更多详细信息,请访问 article in Wikipedia on standard streams (stdin, stdout and stderr) .
关于python - Python 中的实时输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16521575/