python庫asyncio的概念和用法
python 庫 asyncio
asyncio 是 Python 的標準庫之一,用于編寫異步應用程序。它提供了事件循環、協程、任務和其他工具來處理并發操作。以下是一些關于 asyncio 的基本概念和常見用法:
基本概念
- 協程 (Coroutine):
協程是一種特殊的函數,可以暫停執行并在稍后恢復。在 Python 中,協程通常通過 async def 定義。
async def my_coroutine():
print("Hello, World!")
- 事件循環 (Event Loop):
事件循環是 asyncio 的核心,負責管理和調度協程。可以通過 asyncio.run() 啟動事件循環。
import asyncio
async def main():
await my_coroutine()
asyncio.run(main())
- 任務 (Task):
任務是協程的封裝,可以在事件循環中調度和管理。可以通過 asyncio.create_task() 創建任務。
import asyncio
async def my_coroutine():
await asyncio.sleep(1)
print("Task completed")
async def main():
task = asyncio.create_task(my_coroutine())
await task
asyncio.run(main())
常見用法
- 并發執行多個協程:
使用 asyncio.gather() 可以并發執行多個協程,并等待所有協程完成。
import asyncio
async def my_coroutine(id):
await asyncio.sleep(1)
print(f"Coroutine {id} completed")
async def main():
coroutines = [my_coroutine(i) for i in range(3)]
await asyncio.gather(*coroutines)
asyncio.run(main())
- 超時控制:
使用 asyncio.wait_for() 可以設置協程的超時時間。
import asyncio
async def my_coroutine():
await asyncio.sleep(10)
print("This should not be printed")
async def main():
try:
await asyncio.wait_for(my_coroutine(), timeout=5)
except asyncio.TimeoutError:
print("Coroutine timed out")
asyncio.run(main())
- 異步 I/O 操作:
asyncio 提供了異步 I/O 操作的支持,例如 aiohttp 庫可以用于異步 HTTP 請求。
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'https://example.com')
print(html)
asyncio.run(main())
異常處理
在 asyncio 中,異常處理與同步代碼類似,但需要注意的是,協程中的異常需要在 await 時捕獲。
import asyncio
async def my_coroutine():
raise ValueError("An error occurred")
async def main():
try:
await my_coroutine()
except ValueError as e:
print(f"Caught an exception: {e}")
asyncio.run(main())
希望這些示例和解釋能幫助你更好地理解和使用 asyncio。
感謝您的認真閱讀,更多內容請查看:
出處:http://www.rzrgm.cn/weiqinl
個人主頁http://weiqinl.com
github: weiqinl
簡書:weiqinl
您的留言討論是對博主最大的支持!
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
出處:http://www.rzrgm.cn/weiqinl
個人主頁http://weiqinl.com
github: weiqinl
簡書:weiqinl
您的留言討論是對博主最大的支持!
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

浙公網安備 33010602011771號