By robert

2014-10-09 01:08:28 8 Comments

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 | 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?


@Robᵩ 2014-10-09 16:50:03

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"
    #do complicated stuff that takes a long time.

@BiBi 2018-01-27 18:57:19

Great explanation! I would add that calling the script with the flag -u would also solve your problem, e.g. python -u | tee my_file.txt

Related Questions

Sponsored Content

10 Answered Questions

14 Answered Questions

[SOLVED] How do I get a substring of a string in Python?

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3335323 View
  • 2937 Score
  • 42 Answer
  • Tags:   python datetime time

45 Answered Questions

[SOLVED] How to print colored text in Python?

13 Answered Questions

[SOLVED] How to remove a key from a Python dictionary?

24 Answered Questions

[SOLVED] Extracting extension from filename in Python

62 Answered Questions

[SOLVED] Calling an external command from Python

15 Answered Questions

[SOLVED] How to print to stderr in Python?

7 Answered Questions

[SOLVED] How to replicate tee behavior in Python when using subprocess?

44 Answered Questions

[SOLVED] Replacements for switch statement in Python?

Sponsored Content