我有一个写入stdout的脚本,如下所示:
# Send.py
import time
while(1):
print "hello"
time.sleep(0.1)
现在我有另一个需要读取它的脚本:
# Listen.py
while(1) :
print "reading.."
data = sys.stdin.read()
print data
python Send.py | python listen.py
不幸的是,这只是在阅读时停止,并且每次打印都没有。那是为什么?
答案 0 :(得分:3)
read()
方法将一直读到EOF,但第一个程序永远不会结束; read()
将不会返回。
您需要逐行阅读。
替换以下行:
data = sys.stdin.read()
使用:
data = sys.stdin.readline()
除此之外,readline()
将返回带换行符的读取行,print
语句在字符串后面添加新行,从而产生空行。为防止这种情况,请使用sys.stdout.write
:
data = sys.stdin.readline()
sys.stdout.write(data)
<强>更新强>
shell将缓冲输出。要防止它,请刷新输出:
import sys
import time
while 1:
print "hello"
sys.stdout.flush()
time.sleep(0.1)
或者,您可以使用-u
选项使stdout,stderr无缓冲。
python -u send.py | python listen.py
答案 1 :(得分:-1)
这是因为程序尚未终止,而read()
正在等待更多的io。
管道就像一个阻塞插座。
您可能想要查找python队列并使用get_nowait()
这是一个可以帮助您的答案: Non-blocking read on a subprocess.PIPE in python
尝试在python中查找阻塞和非阻塞io。