【发布时间】:2020-02-06 16:52:42
【问题描述】:
我该如何解决先有鸡还是先有蛋的问题?
一个函数将返回生成器的第一个结果,该生成器必须从调用它的函数中收集数据。这适用于一般代码,但是一旦您在循环中抛出异步(我不想返回协程),它就会出错。我如何不从 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
【问题讨论】:
-
为什么不对异步迭代器进行异步迭代呢?您希望
asyncio.run(second_iterator(number))解析到什么值?这段代码的非异步版本是什么?
标签: python python-3.x python-asyncio python-3.7