我是 Python 新手,代码类似于以下内容:
import time
import asyncio
async def my_async_function(i):
print("My function {}".format(i))
async def start():
requests = []
# Create multiple requests
for i in range(5):
print("Creating request #{}".format(i))
requests.append(my_async_function(i))
# Do some additional work here
print("Begin sleep")
time.sleep(10)
print("End sleep")
# Wait for all requests to finish
return await asyncio.gather(*requests)
asyncio.run(start())
无论“额外工作”需要多长时间,请求似乎只在“结束睡眠”之后运行。我猜asyncio.gather是什么实际上开始执行它们。我怎样才能让请求(又名my_async_function())立即开始,做额外的工作,然后等待最后完成?
编辑: 根据 Krumelur 的评论和我自己的发现,我正在寻找以下结果:
import time
import asyncio
import random
async def my_async_function(i):
print("Begin function {}".format(i))
await asyncio.sleep(int(random.random() * 10))
print("End function {}".format(i))
async def start():
requests = []
# Create multiple requests
for i in range(10):
print("Creating request #{}".format(i))
requests.append(asyncio.create_task(my_async_function(i)))
# Do some additional work here
print("Begin sleep")
await asyncio.sleep(5)
print("End sleep")
# Wait for all requests to finish
return await asyncio.gather(*requests)
asyncio.run(start())
这仅my_async_function在“附加工作”都可以等待的情况下才有效,以便事件循环可以为它们中的每一个提供执行时间。你需要create_task(如果你知道它是一个协程)或ensure_future(如果它可能是一个协程或未来)允许请求立即运行,否则它们仍然只有在你gather.