28

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?

robert
  • 1,402
  • 1
  • 15
  • 21
  • 1
    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.com – phemmer Oct 09 '14 at 02:22
  • 1
    May be this helps: http://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe – Ketan Maheshwari Oct 09 '14 at 02:26
  • 1
    at the top do "`import sys`" and on an indented line below the print statement do "`sys.stdout.flush()`" – Anthon Oct 09 '14 at 04:20
  • See also: http://stackoverflow.com/questions/107705/python-output-buffering – Robᵩ Oct 09 '14 at 16:52
  • 8
    The flag `-u` is here to "force stdin, stdout and stderr to be totally unbuffered." and would solve your problem. – BiBi Jan 27 '18 at 18:58

1 Answers1

47

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.
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 46
    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.txt` – BiBi Jan 27 '18 at 18:57