python 文件的标准输出没有实时响应

python stdout to file does not respond in real time

编写一个简单的 python 脚本 test.py:

  import time
  print "begin"
  time.sleep(10)
  print "stop"

在bash, 运行

python test.py > log.txt

我观察到 "begin" 和 "stop" 在 10 秒后同时出现在 log.txt 中。

这是预期的行为吗?

您需要在打印后刷新缓冲区。

import sys
import time

print "begin"
sys.stdout.flush()

time.sleep(10)

print "end"
sys.stdout.flush()

或在Python 3:

# This can also be done in Python 2.6+ with
# from __future__ import print_function

import time

print("begin", flush=True)
time.sleep(10)
print("end", flush=True)

这是因为实际写入仅在缓冲区已满或文件关闭时发生。当程序结束时(10 秒后),缓冲区清空,写入数据并关闭文件。

您是否尝试过使用 -u 选项调用 python,"forces stdin, stdout and stderr to be totally unbuffered" =>

python -u test.py > log.txt