• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

关闭

返回栏目

关闭

返回python栏目

77 - 自带库(3.5) - 异步asyncio - async,await关键字

作者:

贺及楼

成为作者

更新日期:2024-10-27 18:06:26

异步asyncio - async,await关键字

asyncio库的简介

Python 的 asyncio 库是用于编写单线程并发代码的库,使用 async/await 语法。它支持异步I/O、事件循环、协程和任务。asyncio 使得可以在单线程内高效执行并发操作,特别适用于I/O密集型和高级别的结构化网络代码。它简化了异步编程模型,提高了程序性能和响应速度,是实现异步编程的关键工具。

协程使用

python3.4就有asyncio,python3.5用async,await关键字

  1. import time
  2. import asyncio
  3. # 定义异步函数
  4. async def hello():
  5. await asyncio.sleep(1)
  6. print(time.time())
  7. def run():
  8. for i in range(5):
  9. loop.run_until_complete(hello())
  10. loop = asyncio.get_event_loop()
  11. if __name__ =='__main__':
  12. run()
  1. 1527595104.8338501
  2. 1527595104.8338501
  3. 1527595104.8338501
  4. 1527595104.8338501
  5. 1527595104.8338501

async def 用来定义异步函数,其内部有异步操作。
每个线程有一个事件循环,主线程调用asyncio.get_event_loop()时会创建事件循环
你需要把异步的任务丢给这个循环的run_until_complete()方法,事件循环会安排协同程序的执行。

  1. import time
  2. import asyncio
  3. import aiohttp # 用异步方式获取网页内容
  4. urls = ['https://www.baidu.com'] * 400
  5. async def get_html(url, sem):
  6. async with(sem):
  7. async with aiohttp.ClientSession() as session:
  8. async with session.get(url) as resp:
  9. html = await resp.text()
  10. def main():
  11. loop = asyncio.get_event_loop() # 获取事件循环
  12. sem = asyncio.Semaphore(10) # 控制并发的数量
  13. tasks = [get_html(url, sem) for url in urls] # 把所有任务放到一个列表中
  14. loop.run_until_complete(asyncio.wait(tasks)) # 激活协程
  15. loop.close() # 关闭事件循环
  16. if __name__ == '__main__':
  17. start = time.time()
  18. main()
  19. print(time.time()-start) # 5.03s

html = await xxx
html可以获得参数