20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊

👨‍💻 一个真正实用、优雅、能日常用的 Python 小工具!


🚩 希望效果预览

bash 复制代码
$ python weather.py 北京
📍 北京
🌤 多云   28°C
💨 北风 3级   💧 湿度 45%
🕐 更新时间:2025-07-02 14:00

❌ 不过 这个改了 url 换一个 直接使用 免费 api

python 复制代码
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. 项目结构

bash 复制代码
weather/
├── weather.py        # 主文件
├── icons.py          # 图标映射
└── config.py         # API KEY 配置

🔧 2. 注册天气 API(和风天气)

  • 官网:dev.qweather.com
  • 注册后 → 创建应用 → 获取「KEY
  • 使用免费接口即可(每分钟 60 次)

💡 3. config.py 示例

python 复制代码
API_KEY = "你的和风天气 key"

🎨 4. 图标文件:icons.py

python 复制代码
weather_icons = {
    "晴": "☀️", "多云": "⛅", "阴": "☁️", "小雨": "🌧️", "中雨": "🌧️", 
    "大雨": "🌧️", "暴雨": "🌧️", "雷阵雨": "⛈️", "雪": "❄️"
}

🚀 5. 核心代码:weather.py

python 复制代码
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. 运行方式

bash 复制代码
python weather.py 上海

📦 可选优化方向

功能 说明
✅ 多语言支持 支持中英文显示
✅ 添加颜色输出 使用 colorama 彩色打印
✅ 支持多日天气 请求 3~7 天接口数据
✅ 打包 CLI 工具 argparse 支持参数解析、封装成命令行工具
✅ 支持定时更新日报 搭配 schedule 写入 report_xxx.txt
相关推荐
tan180°2 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
优创学社23 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
why技术3 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理3 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
烛阴4 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼4 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开4 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
ai小鬼头4 小时前
AIStarter如何助力用户与创作者?Stable Diffusion一键管理教程!
后端·架构·github
简佐义的博客4 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang