【问题标题】:asyncio get result from coroutineasyncio 从协程中获取结果
【发布时间】: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()
  • 我明白了,谢谢
  • 如果你用解释的解决方案来回答你的问题——它可能对其他人有用:)

标签: python-3.x python-asyncio


【解决方案1】:

在 asyncio.Queue() 的帮助下找到了解决方案

import asyncio

@asyncio.coroutine
def get_work(task, work_queue):
    while not work_queue.empty():
        print(task)
        queue_item = yield from work_queue.get()
        print('{0} grabbed item: {1}'.format(task, queue_item))
        yield from asyncio.sleep(0.5)
    asyncio.async(get_work(task, work_queue))

# @asyncio.coroutine

i = 0
async def do_work(task, work_queue):
    global i
    print(task)
    while work_queue.empty():
        work_queue.put_nowait(i)
        i += 1
        await asyncio.sleep(2)
        break
    # asyncio.async(do_work())
    print("Dfgdfg")
    asyncio.ensure_future(do_work(task, work_queue))




if __name__ == "__main__":
    queue_obj = asyncio.Queue()
    loop = asyncio.get_event_loop()

    tasks = [
        asyncio.async(do_work('Run do_work', queue_obj)),
        asyncio.async(get_work('Run get_work', queue_obj))]

    loop.run_until_complete(asyncio.wait(tasks))
    loop.run_forever()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2020-10-10
    • 2018-07-26
    相关资源
    最近更新 更多