Search code examples
pythonbashbufferio-redirection

Save python log in a file is not real time


In bash I can run something like this ....

~> ping google.com >> log.txt

In log.txt:

PING google.com (216.239.38.120) 56(84) bytes of data.
64 bytes from any-in-2678.1e100.net (216.239.38.120): icmp_seq=1 ttl=104 time=64.2 ms
64 bytes from any-in-2678.1e100.net (216.239.38.120): icmp_seq=2 ttl=104 time=61.5 ms
... (real time like a stream)

But when I run apython file, It doesn't work like ping
Example:

#ding.py
from time import sleep
while True :
    print('ding')
    sleep(0.7)

Run:

~> python ding.py
#ding
#ding 
# ....

But run with >> :

~> python ding.py >> log.txt

In log.txt

<nothing>

And after I click on Ctrl + C , lots of ding appears in log.txt
In log.txt after Ctrl + C:

ding
ding
ding
.....
#log.txt becomes full in a secound

Thank's for your attention


Solution

  • It looks like stdout is not being flushed often enough. Usually it's not a big problem, but if it's important to you, try adding flush=True to your print calls or running python with -u flag to force stdin/stdout to be unbuffered.

    Related question: How can I flush the output of the print function?