Python+API打造一个终端天气预报工具
作者:金泽宸
这篇文章主要为大家详细介绍了如何利用Python和API打造一个终端天气预报工具,支持城市查询,天气图标,美化输出,有需要的小伙伴可以了解一下
一个真正实用、优雅、能日常用的 Python 小工具!
希望效果预览
$ python weather.py 北京
📍 北京
🌤 多云 28°C
💨 北风 3级 💧 湿度 45%
🕐 更新时间:2025-07-02 14:00
不过 这个改了 url 换一个 直接使用 免费 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]❗ 请提供城市名,例如: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,风速:{cw['windspeed']}km/h,风向:{cw['winddirection']}°") except Exception as e: console = Console() console.print(f"[red]❌ 错误:{e}[/]") if __name__ == "__main__": main()
1. 项目结构
weather/
├── weather.py # 主文件
├── icons.py # 图标映射
└── config.py # API KEY 配置
2. 注册天气 API(和风天气)
- 官网:dev.qweather.com
- 注册后 → 创建应用 → 获取「KEY」
- 使用免费接口即可(每分钟 60 次)
3. config.py 示例
API_KEY = "你的和风天气 key"
4. 图标文件: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']}级 💧 湿度 {now['humidity']}%") print(f"🕐 更新时间:{weather['updateTime'][11:16]}") if __name__ == "__main__": if len(sys.argv) < 2: print("❗请输入城市名: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. 运行方式
python weather.py 上海
可选优化方向
功能 | 说明 |
---|---|
多语言支持 | 支持中英文显示 |
添加颜色输出 | 使用 colorama 彩色打印 |
支持多日天气 | 请求 3~7 天接口数据 |
打包 CLI 工具 | 用 argparse 支持参数解析、封装成命令行工具 |
支持定时更新日报 | 搭配 schedule 写入 report_xxx.txt |
到此这篇关于Python+API打造一个终端天气预报工具的文章就介绍到这了,更多相关Python天气预报内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!