python asyncio asyncio wait

import asyncio
import time
async def get_html(url):
    print("start get url")
    await asyncio.sleep(2) # 不能使用time.sleep(),这样的话是同步,就不是异步;await就相当于yield from
    print("end get url")

if __name__ == "__main__":
    start_time = time.time()
    loop = asyncio.get_event_loop()
    tasks = [get_html("http://www.imooc.com") for i in range(10)]
  loop.run_until_complete(asyncio.wait(tasks)) #loop.run_until_complete将task放到loop中,进行事件循环, 这里必须传入的是一个list
print(time.time()-start_time)

 

posted @ 2019-07-20 10:32  下路派出所  阅读(2402)  评论(0编辑  收藏  举报