Write a simple python script test.py:
import time
print "begin"
time.sleep(10)
print "stop"
In bash, run
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.
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:
# 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.