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

Python+API打造一個終端天氣預報工具

 更新時間:2025年07月08日 09:04:39   作者:金澤宸  
這篇文章主要為大家詳細介紹了如何利用Python和API打造一個終端天氣預報工具,支持城市查詢,天氣圖標,美化輸出,有需要的小伙伴可以了解一下

一個真正實用、優(yōu)雅、能日常用的 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]? 請?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,風速:{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
  • 注冊后 → 創(chuàng)建應用 → 獲取「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 上海

可選優(yōu)化方向

功能說明
多語言支持支持中英文顯示
添加顏色輸出使用 colorama 彩色打印
支持多日天氣請求 3~7 天接口數據
打包 CLI 工具用 argparse 支持參數解析、封裝成命令行工具
支持定時更新日報搭配 schedule 寫入 report_xxx.txt

到此這篇關于Python+API打造一個終端天氣預報工具的文章就介紹到這了,更多相關Python天氣預報內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

洪洞县| 宜兰市| 常德市| 体育| 延津县| 平湖市| 西城区| 星座| 江油市| 依兰县| 马龙县| 榕江县| 九台市| 兰考县| 九龙县| 虎林市| 伊川县| 阳新县| 陵水| 古田县| 九龙县| 江北区| 壶关县| 谷城县| 江川县| 武胜县| 磐石市| 焦作市| 昌乐县| 谷城县| 梨树县| 扎赉特旗| 北票市| 内丘县| 吴忠市| 米脂县| 宁陕县| 丹江口市| 历史| 南充市| 青阳县|