Sait
Sait

Reputation: 19815

Only pipe when data arrives

I trying to learn simple piping stuff on Linux:

sender.py:

# sender.py
import random
import sys
import time

while True:
    r = random.randrange(5)
    print(r)
    sys.stdout.flush()
    time.sleep(1)

receiver.py:

# receiver.py
import sys

while True:
    line = sys.stdin.readline()
    print("hello " + line.strip() + " hello")
    sys.stdout.flush()

When I do:

$ python sender.py | python receiver.py

I have the following output as expected:

hello 3 hello
hello 2 hello
hello 2 hello
hello 0 hello
...
^C

Until now, everything works as expected to me. The problematic part is the following. When I try to do:

$ echo "50" | python receiver.py

The output I expect to have is:

hello 50 hello

However, instead, I have the following line occurs infinitely many times:

hello  hello

My questions:

  1. What is going on? What is the logic behind "echo "50" | python receiver.py" ?
  2. Is there a way to change my receiver.py so that it only prints hello 50 hello once?

Upvotes: 1

Views: 73

Answers (2)

user3657941
user3657941

Reputation:

From the documentation:

...if f.readline() returns an empty string, the end of the file has been reached...

Change your code to this:

import sys

while True:
    line = sys.stdin.readline()
    if not len(line):
        break
    print("hello " + line.strip() + " hello")
    sys.stdout.flush()

Upvotes: 1

bosnjak
bosnjak

Reputation: 8624

You are reading the input indefinitely, when there is only one input provided. You need to make your script break when there is nothing received:

# receiver.py
import sys

while True:
    line = sys.stdin.readline()
    if not line:
        break
    print("hello " + line.strip() + " hello")
    sys.stdout.flush()

Upvotes: 1

Related Questions