Anirudh A
Anirudh A

Reputation: 3

Python not printing values in loop

Here is a sample code that I tried running:

import sys
while True:
    print "Hello World"
    #sys.stdout.write("Hello World")
    #sys.stderr.write("Hello World")
    sys.stdout.flush()

This runs fine and prints "Hello World" when ran from the python interpreter. The problem is when I try to run it as follows and writing to a pipe does not work with print and stdout even if I flush the output. It only works when I uncomment the sys.stderr.write().

python test.py | tail -n 1

Kindly note that it only occurs when the print statement is in a loop. Can anyone help me understand why it behaves this way?

Thanks

Upvotes: 0

Views: 710

Answers (1)

Iguananaut
Iguananaut

Reputation: 23306

You're producing endless output and tail -n 1 is waiting for the last line of input from stdin, which never arrives.

Upvotes: 4

Related Questions