2

I have a script that writes to stdout like this:

# Send.py
import time

while(1):
    print "hello"
    time.sleep(0.1)

Now I have another script that needs to read it as such:

# Listen.py
while(1) :

    print "reading.."
    data = sys.stdin.read()
    print data

python Send.py | python listen.py

Unfortunately, this just stops on reading and nothing is every printed. Why is that?

2
  • Probably due to flushing: stackoverflow.com/questions/230751/… Commented Oct 31, 2014 at 14:49
  • Ah Fishsticks. I need to flush after every print, which is only a feature of python 3.3. Dammit! Commented Oct 31, 2014 at 14:52

2 Answers 2

3

read() method will read until EOF, but the first program never end; read() will not return.

You need to read line by line.

Replace the following line:

data = sys.stdin.read()

with:

data = sys.stdin.readline()

In addition to that, readline() will return the read line with newline, and the print statement append new line after the string resulting empty lines inbetween. To prevent that, use sys.stdout.write:

data = sys.stdin.readline()
sys.stdout.write(data)

UPDATE

The shell will buffer output. To prevent it, flush the output:

import sys
import time

while 1:
    print "hello"
    sys.stdout.flush()
    time.sleep(0.1)

Alternatively, you can use -u option to make stdout, stderr unbuffered.

python -u send.py | python listen.py
Sign up to request clarification or add additional context in comments.

7 Comments

Nope. I just tried. still doesnt work. import sys # Listen.py while(1) : print "reading.." data = sys.stdin.readline() print data
This is not working because readline is still blocking until it will receive a \n because the output is finished the readline will continue blocking for ever or until a \n appears (well, that will be never...).
@ovfstack, You may need to flush the output.
readline won't block forever, just BLOCKSIZE / len("hello\n") * .1 seconds, or about 60 seconds.
@user3211152, print statement write the string with a newline (\n)
|
-1

This is because the program has not terminated yet and the read() is waiting for more io. The pipe is like a blocking socket.

you may want to lookup python queues and make use of get_nowait()

Here is a answer that may help you: Non-blocking read on a subprocess.PIPE in python

Try to look up blocking and non-blocking io in python too.

Comments

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.