当生产者耗尽时,有没有办法发出协程?
问题描述:
我正在使用协程管道进行事件驱动的数据管道。到目前为止,一切都很顺利。我想尝试批量处理一些输入,但需要一种方法来确保在上游生产者为空时处理最终批次。在下面的设计示例中,一旦完成produce_data_from
,这将成为print(res)
在print_data_cp
中的一种方式。一个更直接的模拟将是每次打印并重置res
其长度== 3,并且保证在生产者完成后打印res中剩余的值。我知道有几种方法可以解决这个问题,但是有没有一种习惯解决这个问题的方法(例如,前哨值,返回余数,while/finally,wrap in class)?当生产者耗尽时,有没有办法发出协程?
现在,我将coprocess函数作为类的一部分,并让res
为实例变量,以便在coprocess函数完成后可以访问它。这有效,但一段时间/最后会更普遍。
def produce_data_from(data, consumer):
next(consumer)
for x in data:
consumer.send(x)
def print_data_cp():
res = []
while True:
x = (yield)
res.append(x)
print(x)
cons = print_data_cp()
produce_data_from(range(10), cons)
答
此修改使用try/finally并更改生产者关闭消费者协处理。这会触发finally块。在这里,协处理器依赖于生产者发送信号,所以将消费者功能修改为批处理需要修改上游生产者功能。不理想,但它的工作原理和感觉足够pythonic。我很高兴看到其他方法。
def produce_data_from(data, consumer):
next(consumer)
for x in data:
consumer.send(x)
consumer.close()
def print_data_cp():
res = []
try:
while True:
x = (yield)
res.append(x)
if len(res) >= 3:
print(res)
res = []
finally:
print(res)
cons = print_data_cp()
produce_data_from(range(10), cons)