Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tee to get realtime print statements from python [duplicate]

Tags:

python

stdout

tee

I have a python script that looks something like this:

for item in collection:
    print "what up"
    #do complicated stuff that takes a long time.

In bash, I run this script by doing the following:

$ python my.py | tee my_file.txt

However, all I see in bash is a blank line until the program finishes. Then, all of the print statements come all at one.

Is this the expected operation of tee? Can I use tee to see the output in real-time?

like image 545
robert Avatar asked Oct 09 '14 01:10

robert


1 Answers

Python, like many programs, tries to minimize the number of times it calls the write system call. It does this by collecting the output of several print statements before it actually writes them to its standard output file. This process is called buffering the output.

When Python is connected to a terminal, it doesn't buffer its output. This makes sense, because the human at the terminal wants to see the output right away.

When Python is writing to a file (or a pipe), it does buffer its output. This also makes sense, because no one will see the output until the process is complete

You can defeat this optimization by calling sys.stdout.flush() whenever you want to force Python to write its buffered output to its standard output file.

In your case, try this:

import sys
...
for item in collection:
    print "what up"
    sys.stdout.flush()
    #do complicated stuff that takes a long time.
like image 65
Robᵩ Avatar answered Oct 16 '22 02:10

Robᵩ