异步函数调用异步生成器调用异步函数

时间:2020-02-06 16:52:42

标签: python python-3.x python-asyncio python-3.7

我该如何解决鸡肉和鸡蛋的问题?

一个函数将返回生成器的第一个结果,该生成器必须从调用它的函数中收集数据。这在通用代码中有效,但是一旦在循环中抛出异步(我不想返回协程),它就会出错。如何function_one返回协程?

代码:

import asyncio

async def second_iterator(number):
    for x in range(number):
        yield await function_one(x)

async def function_one(number):
    if number > 2:
        return asyncio.run(second_iterator(number))

    await asyncio.sleep(1)
    return number

def main(number):
    print(asyncio.run(function_one(number)))

main(3)

错误:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    main(3)
  File "main.py", line 15, in main
    print(asyncio.run(function_one(number)))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Owner\Anaconda3\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "main.py", line 9, in function_one
    return asyncio.run(second_iterator(number))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 34, in run
    "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop

1 个答案:

答案 0 :(得分:0)

您的脚本中应该只有一个asyncio.run()。这是程序的入口点:

import asyncio


async def main():
    # all your code is here


if __name__ == "__main__":
    asyncio.run(main())

asyncio.run()是启动event loop的唯一阻止操作,该操作管理所有协程和任务的执行。

请考虑阅读有关asyncio的一些教程,它可能有助于您更快地实现目标: