Kiv*_*Kiv 15 python pipe producer-consumer
我正在尝试从管道中读取线条并处理它们,但我正在做一些愚蠢的事情,我无法弄清楚是什么.生产者将无限期地继续生产生产线,如下所示:
producer.py
import time
while True:
print 'Data'
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
消费者只需要定期检查线路:
consumer.py
import sys, time
while True:
line = sys.stdin.readline()
if line:
print 'Got data:', line
else:
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
当我在Windows shell中运行它时python producer.py | python consumer.py,它只是永远睡觉(似乎永远不会得到数据?)似乎问题是生产者永远不会终止,因为如果我发送有限数量的数据然后它工作正常.
如何获取数据并显示给消费者?在实际应用程序中,生产者是一个我无法控制的C++程序.
Ale*_*lli 15
一些旧版本的Windows通过文件模拟管道(因此它们容易出现这样的问题),但这在10年以上并不是问题.尝试添加一个
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
之后的生产者print,并尝试使生产者的stdout无缓冲(通过使用python -u).
当然,如果您无法控制生产者,这无济于事 - 如果它缓冲了太多的输出,您仍然需要等待很长时间.
不幸的是 - 虽然有许多方法可以在类Unix操作系统上解决这个问题,例如pyexpect,pexpect,exscript和paramiko,但我怀疑它们是否适用于Windows; 如果确实如此,我会尝试Cygwin,它在Windows上放置了类似Linux的单板,以便经常在Windows机器上使用类似Linux的方法.
这是关于默认使用Python缓存的I/O. 将-u选项传递给解释器以禁用此行为:
python -u producer.py | python consumer.py
Run Code Online (Sandbox Code Playgroud)
它解决了我的问题.