![](/img/trans.png)
[英]Python - Capturing stdout of a multiple Popen subprocesses in real time to a file
[英]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
我观察到的是,“开始”和“停止”同时出现在log.txt中,10秒后。
这是预期的行为吗?
打印后需要刷新缓冲区。
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)
您是否尝试使用-u选项调用python,“强制stdin,stdout和stderr完全无缓冲”=>
python -u test.py > log.txt
这是因为实际写入仅在缓冲区已满或文件关闭时才会发生。 当程序结束时(10秒后),清空缓冲区,写入数据并关闭文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.