0

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

1
  • Why describe the issue rather than provide runnable code that illustrates the thing that surprises you? Commented Oct 22, 2017 at 22:36

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Iguananaut for the help. It seems I was overthinking. But as a followup, anything but last line will be written to standard error? I have accepted your answer as my primary question has been answered.
I'm not sure--that sounds tricky and might not be doable as a one-liner. Though if you ask that as a separate question I'm sure there's a bash wizard out there who can answer it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.