![](/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.