← 返回首页

用 Python 给自己写一个命令行天气工具

不用任何第三方 SDK,只用标准库加一个免费天气 API,写一个能在终端直接查天气、带缓存和彩色输出的小工具。

想要的功能很简单:打开终端敲 weather 广州,直接看到当前天气和未来三天预报。不装一堆依赖,不超过 150 行代码。

一、选一个无需密钥的接口

wttr.in 支持纯文本和 JSON 两种返回,用 ?format=j1 拿结构化数据:

curl -s 'https://wttr.in/Guangzhou?format=j1' | head -c 400

返回的 JSON 里有 current_condition 和 weather 数组,够用了。

二、拉数据:urllib 就够

import json
import urllib.parse
import urllib.request

def fetch(city: str) -> dict:
    url = "https://wttr.in/" + urllib.parse.quote(city) + "?format=j1"
    req = urllib.request.Request(url, headers={"User-Agent": "cli-weather/1.0"})
    with urllib.request.urlopen(req, timeout=10) as resp:
        return json.loads(resp.read().decode("utf-8"))
一定要设置 User-Agent。不带 UA 的请求会被不少服务直接拒绝,这是新手最常见的坑。

三、加一层缓存

天气数据 30 分钟内变化不大,缓存能显著提速,也避免频繁请求被限流:

import hashlib
import time
from pathlib import Path

CACHE_DIR = Path.home() / ".cache" / "cli-weather"

def cached_fetch(city: str, ttl: int = 1800) -> dict:
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    key = hashlib.md5(city.lower().encode()).hexdigest()
    fp = CACHE_DIR / f"{key}.json"
    if fp.exists() and time.time() - fp.stat().st_mtime < ttl:
        return json.loads(fp.read_text(encoding="utf-8"))
    data = fetch(city)
    fp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
    return data

四、终端彩色输出

ANSI 转义就够了,不必上 rich:

def color(s, code):
    return f"\033[{code}m{s}\033[0m"

print(color("广州", "1;36"), color("26°C", "1;33"))

更稳妥的写法是检测 sys.stdout.isatty(),当输出被重定向到文件时关掉颜色,避免日志里出现乱码。

五、参数解析

import argparse

parser = argparse.ArgumentParser(description="命令行天气查询")
parser.add_argument("city", nargs="?", default="Guangzhou")
parser.add_argument("-d", "--days", type=int, default=3, choices=[1, 2, 3])
parser.add_argument("--no-cache", action="store_true")
args = parser.parse_args()

六、拼装主流程

def main():
    args = parser.parse_args()
    data = fetch(args.city) if args.no_cache else cached_fetch(args.city)
    cur = data["current_condition"][0]
    print(f"{args.city}   {cur['temp_C']}°C   {cur['weatherDesc'][0]['value']}")
    for day in data["weather"][:args.days]:
        print(f"{day['date']}  {day['mintempC']}~{day['maxtempC']}°C  {day['hourly'][4]['weatherDesc'][0]['value']}")

if __name__ == "__main__":
    main()

七、收尾

  • 放到 ~/.local/bin/weather 并 chmod +x,就能全局调用
  • 把网络异常包在 try 里,失败时回退到过期缓存并提示
  • 真要做成产品,再考虑加配置文件放默认城市

这类小工具的价值不在代码量,而在于它逼你把「HTTP 请求 → 解析 → 缓存 → 输出」这条链完整走一遍。走通了,下次接别的 API 都是同样的骨架。