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

1

29

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?

Thermobarometer answered 9/10, 2014 at 1:8 Comment(5)
This is going to be an issue with python. It's deliberate. It's simply detecting that the output isn't going to a terminal, so it's buffering. You need to turn the buffering off. How to do that is probably better suited for stackexchange.comCoricoriaceous
May be this helps: unix.stackexchange.com/questions/25372/…Ayesha
at the top do "import sys" and on an indented line below the print statement do "sys.stdout.flush()"Restivo
See also: https://mcmap.net/q/20922/-disable-output-bufferingIty
The flag -u is here to "force stdin, stdout and stderr to be totally unbuffered." and would solve your problem.Iterative
N
48

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.
Nurture answered 9/10, 2014 at 16:50 Comment(1)
Great explanation! I would add that calling the script with the flag -u would also solve your problem, e.g. python -u my.py | tee my_file.txtIterative

© 2022 - 2024 — McMap. All rights reserved.