【发布时间】:2016-12-16 14:51:21
【问题描述】:
我有一个任务是在 asyncio 和 python3 的帮助下在协程之间进行通信。 请告诉我怎么做,如果一个协程在while tru循环中,以不同的时间间隔返回值,而其他协程接收到这个数据
import asyncio
@asyncio.coroutine
def write(future):
i=0
while True:
yield from asyncio.sleep(1)
future.set_result('data: '.format(i))
i+=1
def got_result(future):
print(future.result())
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(write(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
【问题讨论】:
-
使用
asyncio.Queue -
非常感谢您的帮助。但是如果我要使用队列,我如何在事件中读取它,而不是不断检查队列。它必须按照方法“asyncio.Future().add_done_callback(func)”使用队列
-
最终用户代码不应该调用
.add_done_callback——它的级别太低了。只需while True: await queue.get()。 -
我明白了,谢谢
-
如果你用解释的解决方案来回答你的问题——它可能对其他人有用:)