简体   繁体   English

python stdout to file没有实时响应

[英]python stdout to file does not respond in real time

Write a simple python script test.py: 写一个简单的python脚本test.py:

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

In bash, run 在bash中,运行

python test.py > log.txt

What I observe is that both "begin" and "stop" appear in log.txt at the same time, after 10 seconds. 我观察到的是,“开始”和“停止”同时出现在log.txt中,10秒后。

Is this expected behavior? 这是预期的行为吗?

You need to flush the buffer after printing. 打印后需要刷新缓冲区。

import sys
import time

print "begin"
sys.stdout.flush()

time.sleep(10)

print "end"
sys.stdout.flush()

Or in Python 3: 或者在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)

您是否尝试使用-u选项调用python,“强制stdin,stdout和stderr完全无缓冲”=>

python -u test.py > log.txt

This is because the actual writing happens only when a buffer is full, or when the file is closed. 这是因为实际写入仅在缓冲区已满或文件关闭时才会发生。 When the program ends (after 10s), the buffer is emptied, the data gets written and the file closed. 当程序结束时(10秒后),清空缓冲区,写入数据并关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM