Python asyncio 非同步程式完整教學:從 async/await 到實戰應用一次搞懂
如果你寫 Python 寫了一段時間,一定碰過這種情境:程式需要同時發送好幾個 API 請求,但用傳統的同步寫法只能一個一個慢慢等。這時候 asyncio 就是你的救星。
老實說,我第一次接觸 asyncio 的時候也是一頭霧水。但花了兩個專案的時間摸索之後,我現在覺得這真的是每個 Python 開發者都該學的技能。
什麼是 asyncio?為什麼你需要它
asyncio 是 Python 標準庫中的非同步 I/O 框架。它讓你在單一執行緒中同時處理多個 I/O 操作。跟 threading 最大的差別是 asyncio 使用協作式多工,沒有 race condition 問題。
如果你之前學過 Python Selenium 動態爬蟲,你一定知道等待頁面載入有多浪費時間。asyncio 就是解決這類等待問題的利器。
同步 vs 非同步:一個煮泡麵的比喻
想像你在煮三碗泡麵。同步:一碗一碗慢慢等,要花三倍時間。非同步:同時燒三壺水,總時間跟煮一碗差不多。
async/await 基礎語法教學
import asyncio
async def fetch_data(url):
print(f"開始請求 {url}")
await asyncio.sleep(2)
print(f"完成請求 {url}")
return f"{url} 的資料"
async def main():
result = await fetch_data("https://api.example.com")
print(result)
asyncio.run(main())重點:async def 定義協程函式,await 暫停當前協程,asyncio.run() 是進入點。
Event Loop 事件迴圈的運作原理
Event Loop 是 asyncio 的心臟,不斷檢查準備好的協程、執行它們、把控制權交給下一個。
async def task(name, seconds):
print(f"任務 {name} 開始")
await asyncio.sleep(seconds)
print(f"任務 {name} 完成")
async def main():
await asyncio.gather(task("A", 3), task("B", 1), task("C", 2))
asyncio.run(main())TaskGroup 結構化併發(Python 3.11+)
Python 3.11 引入的 TaskGroup,提供更好的錯誤處理。
async def main():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(fetch_data("url1"))
task2 = tg.create_task(fetch_data("url2"))
print(task1.result(), task2.result())asyncio.gather 同時執行多個協程
results = await asyncio.gather(
fetch_data("url1"), fetch_data("url2"),
return_exceptions=True
)實戰:用 aiohttp 做非同步 HTTP 請求
import aiohttp, asyncio
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ["https://httpbin.org/delay/1", "https://httpbin.org/delay/2"]
async with aiohttp.ClientSession() as session:
results = await asyncio.gather(*[fetch_url(session, u) for u in urls])
asyncio.run(main())如果你在做排程自動化,asyncio 搭配 aiohttp 是絕配。
新手常見的 5 個錯誤
- 忘記 await
- 用 time.sleep 而不是 asyncio.sleep
- 把 CPU 密集任務丟進 asyncio
- 手動管理 event loop
- 沒有處理例外
什麼時候該用 asyncio?
| 場景 | 建議 |
|---|---|
| 大量 API 呼叫 | asyncio + aiohttp |
| Web 框架 | FastAPI |
| 爬蟲 | asyncio + httpx |
| 數值計算 | multiprocessing |
如果你正在學 FastAPI 建立 REST API,asyncio 幾乎是必學的。
結語
如果你是 Python 新手,建議先把虛擬環境搞熟,再來學 asyncio。
繼續閱讀
Python uv 套件管理器完全教學:比 pip 快 100 倍的新選擇
相關文章
你可能也喜歡
探索其他領域的精選好文