当前位置:   article > 正文

python asyncio wait和gather

asyncio gather python

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)

 

转载于:https://www.cnblogs.com/callyblog/p/11217158.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/102685
推荐阅读
相关标签
  

闽ICP备14008679号