python stdout to file does not respond in real time python stdout to file does not respond in real time bash bash

python stdout to file does not respond in real time


Have you tried calling python with the -u option, which "forces stdin, stdout and stderr to be totally unbuffered" =>

python -u test.py > log.txt


You need to flush the buffer after printing.

import sysimport timeprint "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_functionimport timeprint("begin", flush=True)time.sleep(10)print("end", flush=True)


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.