Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to pipe python output to program

Tags:

python

linux

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!

like image 765
Thomas Højriis Knudsen Avatar asked Aug 29 '16 18:08

Thomas Højriis Knudsen


1 Answers

You'll need to flush the stdout:

import time
import sys

while True:
    print("Hello!")
    sys.stdout.flush()
    time.sleep(1)
like image 132
Robert Seaman Avatar answered Nov 04 '22 16:11

Robert Seaman