Python+API打造一個(gè)終端天氣預(yù)報(bào)工具
一個(gè)真正實(shí)用、優(yōu)雅、能日常用的 Python 小工具!
希望效果預(yù)覽
$ python weather.py 北京
?? 北京
?? 多云 28°C
?? 北風(fēng) 3級(jí) ?? 濕度 45%
?? 更新時(shí)間:2025-07-02 14:00
不過 這個(gè)改了 url 換一個(gè) 直接使用 免費(fèi) api
import requests
import sys
from rich import print
from rich.console import Console
def get_coords(city):
# geocoding 用 nominatim(OpenStreetMap 無 KEY)
r = requests.get(
"https://geocode.maps.co/search",
params={"q": city}
)
data = r.json()
if not data:
raise Exception("城市未找到")
return data[0]["lat"], data[0]["lon"]
def get_weather(lat, lon):
r = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={"latitude": lat, "longitude": lon,
"current_weather": True}
)
return r.json()["current_weather"]
def main():
if len(sys.argv) < 2:
print("[red]? 請(qǐng)?zhí)峁┏鞘忻?,例如:python weather.py 北京[/]")
return
city = sys.argv[1]
try:
lat, lon = get_coords(city)
cw = get_weather(lat, lon)
console = Console()
console.print(f"?? [bold magenta]{city}[/]")
console.print(f"?? 溫度:{cw['temperature']}°C,風(fēng)速:{cw['windspeed']}km/h,風(fēng)向:{cw['winddirection']}°")
except Exception as e:
console = Console()
console.print(f"[red]? 錯(cuò)誤:{e}[/]")
if __name__ == "__main__":
main()
1. 項(xiàng)目結(jié)構(gòu)
weather/
├── weather.py # 主文件
├── icons.py # 圖標(biāo)映射
└── config.py # API KEY 配置
2. 注冊(cè)天氣 API(和風(fēng)天氣)
- 官網(wǎng):dev.qweather.com
- 注冊(cè)后 → 創(chuàng)建應(yīng)用 → 獲取「KEY」
- 使用免費(fèi)接口即可(每分鐘 60 次)
3. config.py 示例
API_KEY = "你的和風(fēng)天氣 key"
4. 圖標(biāo)文件:icons.py
weather_icons = {
"晴": "??", "多云": "?", "陰": "??", "小雨": "???", "中雨": "???",
"大雨": "???", "暴雨": "???", "雷陣雨": "??", "雪": "??"
}
5. 核心代碼:weather.py
import requests, sys
from config import API_KEY
from icons import weather_icons
def get_city_code(city):
url = f"https://geoapi.qweather.com/v2/city/lookup?location={city}&key={API_KEY}"
r = requests.get(url)
data = r.json()
if "location" in data:
return data["location"][0]["id"]
return None
def get_weather(city_id):
url = f"https://devapi.qweather.com/v7/weather/now?location={city_id}&key={API_KEY}"
r = requests.get(url)
return r.json()
def display(city, weather):
now = weather["now"]
text = now["text"]
icon = weather_icons.get(text, "")
print(f"?? {city}")
print(f"{icon} {text} {now['temp']}°C")
print(f"?? {now['windDir']} {now['windScale']}級(jí) ?? 濕度 {now['humidity']}%")
print(f"?? 更新時(shí)間:{weather['updateTime'][11:16]}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("?請(qǐng)輸入城市名:python weather.py 北京")
sys.exit(1)
city = sys.argv[1]
city_id = get_city_code(city)
if not city_id:
print("? 城市不存在")
sys.exit(1)
weather = get_weather(city_id)
display(city, weather)
6. 運(yùn)行方式
python weather.py 上海
可選優(yōu)化方向
| 功能 | 說明 |
|---|---|
| 多語言支持 | 支持中英文顯示 |
| 添加顏色輸出 | 使用 colorama 彩色打印 |
| 支持多日天氣 | 請(qǐng)求 3~7 天接口數(shù)據(jù) |
| 打包 CLI 工具 | 用 argparse 支持參數(shù)解析、封裝成命令行工具 |
| 支持定時(shí)更新日?qǐng)?bào) | 搭配 schedule 寫入 report_xxx.txt |
到此這篇關(guān)于Python+API打造一個(gè)終端天氣預(yù)報(bào)工具的文章就介紹到這了,更多相關(guān)Python天氣預(yù)報(bào)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Keras保存模型并載入模型繼續(xù)訓(xùn)練的實(shí)現(xiàn)
這篇文章主要介紹了Keras保存模型并載入模型繼續(xù)訓(xùn)練的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
pandas中數(shù)據(jù)缺失值的檢測(cè),統(tǒng)計(jì)與處理教學(xué)
數(shù)據(jù)缺失指的是數(shù)據(jù)中的某個(gè)或某些特征不完整,即由于各種原因?qū)е聰?shù)據(jù)記錄中某些列的值空缺,本文整理了pandas?中常見的數(shù)據(jù)缺失值的檢測(cè)、統(tǒng)計(jì)與處理方法,希望對(duì)大家有所幫助2026-04-04
Python光學(xué)仿真wxpython透鏡演示系統(tǒng)計(jì)算與繪圖
這篇文章主要為大家介紹了Python光學(xué)仿真wxpython透鏡演示系統(tǒng)計(jì)算與繪圖的實(shí)現(xiàn)示例。有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
echarts折線圖的每個(gè)折點(diǎn)都顯示數(shù)值的實(shí)現(xiàn)方式
這篇文章主要介紹了echarts折線圖的每個(gè)折點(diǎn)都顯示數(shù)值的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
快速了解Python開發(fā)中的cookie及簡(jiǎn)單代碼示例
這篇文章主要介紹了快速了解Python開發(fā)中的cookie及簡(jiǎn)單代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-03-03
python?flask項(xiàng)目打包成docker鏡像發(fā)布的過程
這篇文章主要介紹了python?flask項(xiàng)目打包成docker鏡像發(fā)布,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03

