【发布时间】:2019-03-22 05:35:10
【问题描述】:
拥有一个异步生成器,我希望能够异步迭代它。但是,我遗漏了一些东西或弄乱了一些东西,或者两者兼而有之,因为我最终得到了一个常规的同步 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
【问题讨论】:
标签: python loops for-loop asynchronous python-asyncio