【发布时间】:2017-02-24 21:13:54
【问题描述】:
我尝试在 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()
当我这样做时:
$ python sender.py | python receiver.py
我有如下预期的输出:
hello 3 hello
hello 2 hello
hello 2 hello
hello 0 hello
...
^C
到目前为止,一切正常。有问题的部分如下。当我尝试这样做时:
$ echo "50" | python receiver.py
我期望的输出是:
hello 50 hello
但是,相反,我有以下行无限次出现:
hello hello
我的问题:
- 这是怎么回事? "echo "50" | python receiver.py" 背后的逻辑是什么?
- 有没有办法改变我的 receiver.py 使其只打印一次
hello 50 hello?
【问题讨论】: