python asyncio wait和gather
1. wait, 等待某某执行完成以后才执行下一步
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
import asyncio import time async def get_html(term): print("start get url") await asyncio.sleep(term) print("end get url") if __name__ == '__main__': group1 = [get_html(i) for i in range(10)] loop = asyncio.get_event_loop() import concurrent.futures loop.run_until_complete(asyncio.wait(group1, return_when=concurrent.futures.FIRST_COMPLETED)) print(1)
2. gather 比wait更加高级,可以将任务分组,并且取消掉,取消时,必须设置 return_exception为True,不然会抛异常
import asyncio import time async def get_html(url): print("start get url") await asyncio.sleep(2) print("end get url") if __name__ == "__main__": start_time = time.time() loop = asyncio.get_event_loop() #gather和wait的区别 #gather更加high-level group1 = [get_html("http://projectsedu.com") for i in range(2)] # 分组 group2 = [get_html("http://www.imooc.com") for i in range(2)] group1 = asyncio.gather(*group1) group2 = asyncio.gather(*group2) group2.cancel() loop.run_until_complete(asyncio.gather(group1, group2, return_exceptions=True)) print(time.time() - start_time)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步