Python 只有在数据到达时才使用管道
我正在尝试学习Linux上的简单管道功能: sender.py:Python 只有在数据到达时才使用管道,python,linux,pipe,Python,Linux,Pipe,我正在尝试学习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 import sys while True: line = sys.stdin.readline()
# sender.py
import random
import sys
import time
while True:
r = random.randrange(5)
print(r)
sys.stdout.flush()
time.sleep(1)
# receiver.py
import sys
while True:
line = sys.stdin.readline()
print("hello " + line.strip() + " hello")
sys.stdout.flush()
receiver.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
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
我的问题是:
hello 50 hello
当只提供一个输入时,您将无限期地读取输入。当没有收到任何内容时,您需要使脚本
中断:
# receiver.py
import sys
while True:
line = sys.stdin.readline()
if not line:
break
print("hello " + line.strip() + " hello")
sys.stdout.flush()
发件人:
…如果f.readline()返回空字符串,则已到达文件结尾
将代码更改为:
import sys
while True:
line = sys.stdin.readline()
if not len(line):
break
print("hello " + line.strip() + " hello")
sys.stdout.flush()