最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python+API打造一個(gè)終端天氣預(yù)報(bào)工具

 更新時(shí)間:2025年07月08日 09:04:39   作者:金澤宸  
這篇文章主要為大家詳細(xì)介紹了如何利用Python和API打造一個(gè)終端天氣預(yù)報(bào)工具,支持城市查詢,天氣圖標(biā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)文章

最新評(píng)論

鄂托克前旗| 丹寨县| 通榆县| 平果县| 海口市| 高州市| 精河县| 佛坪县| 临漳县| 视频| 曲松县| 平乐县| 陈巴尔虎旗| 福泉市| 新乡市| 浦城县| 鄂托克前旗| 宁都县| 水富县| 湘潭县| 三亚市| 博客| 南和县| 灯塔市| 建瓯市| 邹城市| 洛浦县| 神池县| 朝阳市| 柯坪县| 习水县| 广西| 江城| 定陶县| 江永县| 水城县| 南木林县| 南郑县| 东源县| 桐柏县| 郑州市|