Thomas Højriis Knudsen Thomas Højriis Knudsen - 3 months ago 17
Linux Question

Unable to pipe python output to program

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!

Answer

You'll need to flush the stdout:

import time
import sys

while True:
    print("Hello!")
    sys.stdout.flush()
    time.sleep(1)
Comments