6

I want to pipe stdout from python to another program, but I am faceing a problem where my stdout is not piped.

I have it shortened down to a simple sample:

import time

while True:
    print("Hello!")
    time.sleep(1)

I check it with cat like so:

./my_python_script.py | cat

And then I get nothing at all.

Strange thing is that it works just fine if i remove the sleep command. However, I do not want to pipe the output that fast, so I would really like to sleep for a second.

I checked with the corresponding bash script:

while true; do
    echo "Hello!"
    sleep 1
done

And that works like a charm too. So any idea as to why the python script does not pipe the output as expected? Thanks!

1
  • 4
    By default, pipes only send data when their buffer fills up (usually 8K). Your example would have worked eventually, if you had waited long enough. Your non-sleep example worked because it filled up the buffer immediately. Commented Aug 29, 2016 at 18:16

1 Answer 1

15

You'll need to flush the stdout:

import time
import sys

while True:
    print("Hello!")
    sys.stdout.flush()
    time.sleep(1)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer. I had a feeling it had to do with buffer not filling up fast enough

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.