快速上手
安裝 cwa、設定授權碼並查詢第一筆天氣。
cwa 讓你用地名查詢中央氣象署的開放資料。本頁帶你完成安裝、設定授權碼,並查詢一個鄉鎮的天氣。
安裝
需要 Python 3.13 以上版本。
pip install cwa 使用 uv 則執行 uv add cwa。
選用功能
基本安裝已涵蓋查詢功能。下列功能需要額外套件,以 pip install "cwa[polars]" 的形式安裝:
| 額外套件 | 提供的功能 | 未安裝時 |
|---|---|---|
cwa[polars] | to_polars() 匯出 | 呼叫時引發 MissingDependencyError |
cwa[pandas] | to_pandas() 匯出 | 呼叫時引發 MissingDependencyError |
cwa[arrow] | to_arrow() 匯出 | 呼叫時引發 MissingDependencyError |
cwa[geo] | 依座標比對警特報範圍 | 依座標查詢警特報時引發 MissingDependencyError;依縣市或鄉鎮查詢不受影響 |
cwa[fast] | 以 PyProj 計算距離,大量計算時快數十倍 | 改用 GeographicLib,結果相同 |
cwa[all] | 以上全部 |
授權碼
至CWA_API_KEY 讀取授權碼,依作業系統設定:
# macOS、Linux
export CWA_API_KEY="授權碼" # Windows PowerShell
$env:CWA_API_KEY = "授權碼" 若授權碼來自設定檔或密鑰管理服務,不方便設成環境變數,可在建立用戶端時傳入。cwa.weather.get() 等模組函式只讀取環境變數,此時須改用用戶端:
from cwa import CWA
with CWA(api_key="授權碼") as client:
weather = client.weather.get("臺北市信義區") 用戶端的其他用途見
第一個查詢
cwa.weather.get() 一次取得一個鄉鎮的預報、目前天氣及警特報:
import cwa
weather = cwa.weather.get("臺北市信義區")
if weather.current:
print(weather.current.station.name, weather.current.temperature)
if weather.tomorrow:
print(weather.tomorrow.temperature.max, weather.tomorrow.precipitation.max_probability)
for alert in weather.alerts:
print(alert.title) | 欄位 | 內容 | 可能為 None 的情況 |
|---|---|---|
current | 鄰近測站的最新觀測值 | 10 公里內沒有兩小時內的觀測值 |
today、tomorrow | 今天及明天的預報 | 預報未涵蓋該日 |
alerts | 影響此鄉鎮的警特報,可直接以 for 逐一取出 | 不會是 None,沒有警特報時為空 |
使用可能為 None 的欄位前,請先以 if 確認,如上例所示。每個欄位的完整說明見