拥有一个异步生成器,我希望能够异步地迭代它。然而,我可能错过了某些东西,或者弄错了什么,最终我得到的是一个常规的同步for循环:
import asyncio
async def time_consuming(t):
print(f"Going to sleep for {t} seconds")
await asyncio.sleep(t)
print(f"Slept {t} seconds")
return t
async def generator():
for i in range(4, 0, -1):
yield await time_consuming(i)
async def consumer():
async for t in generator():
print(f"Doing something with {t}")
if __name__ == '__main__':
loop = asyncio.new_event_loop()
loop.run_until_complete(consumer())
loop.close()
这将需要大约12秒钟来运行并返回以下内容:
Going to sleep for 4 seconds
Slept 4 seconds
Doing something with 4
Going to sleep for 3 seconds
Slept 3 seconds
Doing something with 3
Going to sleep for 2 seconds
Slept 2 seconds
Doing something with 2
Going to sleep for 1 seconds
Slept 1 seconds
Doing something with 1
尽管我预计它需要大约4秒钟才能运行并返回类似以下的内容:
Going to sleep for 4 seconds
Going to sleep for 3 seconds
Going to sleep for 2 seconds
Going to sleep for 1 seconds
Slept 4 seconds
Doing something with 4
Slept 3 seconds
Doing something with 3
Slept 2 seconds
Doing something with 2
Slept 1 seconds
Doing something with 1
asyncio.create_task()
一样简单。 - Martijn Pietersdone
就拥有了我们所需的所有信息。 - Martijn Pieters