萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 終端機查詢天氣預報:wego、curl wttr.in 與 Shell 腳本整合

方案一:wego (Go 語言、ncurses 介面、多日預報)

安裝

# 1. 安裝 Go (>=1.16)
sudo apt install golang-go   # 或從 golang.org 下載

# 2. 安裝 wego
go install github.com/schachmat/wego@latest
# 二進位在 ~/go/bin/wego

# 3. 加入 PATH
echo 'export PATH=$PATH:~/go/bin' >> ~/.bashrc
source ~/.bashrc

配置 API Key

  1. 註冊 WorldWeatherOnline 免費 API (每日 250 次額度)。
  2. 首次執行 wego 會產生 ~/.wegorc,編輯填入 Key:
{
  "APIKey": "YOUR_API_KEY",
  "City": "Taipei",
  "Language": "zh",
  "Days": 3
}

使用

wego              # 3 天預報
wego 5            # 5 天預報
wego "New York"   # 指定城市

wego 終端機介面

常見錯誤:user.Current not implemented

# 環境不支援原生 Go 編譯器 (如某些容器/嵌入式)
sudo apt install gccgo-go
go install -compiler=gccgo github.com/schachmat/wego@latest

方案二:curl + wttr.in (零安裝、極簡、支援 ANSI 色彩)

# 當地天氣 (自動偵測 IP)
curl wttr.in

# 指定城市
curl wttr.in/Taipei
curl wttr.in/"Taipei,Taiwan"

# 僅顯示當前天氣 (單行)
curl wttr.in/Taipei?format=3
# 輸出: Taipei: ☀️ +28°C

# 只看未來 3 天
curl wttr.in/Taipei?0

# 關閉顏色 (管道/腳本)
curl -s wttr.in/Taipei?format=3

# 獲取 JSON (程式處理)
curl -s "wttr.in/Taipei?format=j1" | jq .

wttr.in 進階參數

參數說明
?0僅當前天氣
?1當前 + 1 天
?2當前 + 2 天
?n當前 + n 天
?format=3單行摘要
?format=j1JSON 格式
?lang=zh中文輸出
?u美制單位 (mph/°F)
?m公制單位 (km/h/°C)

方案三:Shell 腳本整合到狀態列 / 通知

Polybar / i3blocks / Waybar 模組

#!/bin/bash
# weather-module.sh
CACHE="/tmp/weather_cache"
if [ ! -f "$CACHE" ] || [ $(( $(date +%s) - $(stat -c %Y "$CACHE") )) -gt 1800 ]; then
  curl -s "wttr.in/Taipei?format=3&lang=zh" > "$CACHE"
fi
cat "$CACHE"

桌面通知 (cron 定時推送)

# ~/.local/bin/weather-notify.sh
notify-send "天氣預報" "$(curl -s 'wttr.in/Taipei?0&lang=zh')"

# crontab -e
0 7 * * * DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus /home/user/.local/bin/weather-notify.sh

方案四:Python 腳本 (自定義格式、多城市)

#!/usr/bin/env python3
import requests, json, sys

def get_weather(city="Taipei", days=3):
    url = f"https://wttr.in/{city}?format=j1"
    r = requests.get(url, timeout=5)
    data = r.json()
    curr = data['current_condition'][0]
    print(f"{city}: {curr['weatherDesc'][0]['value']} {curr['temp_C']}°C "
          f"Feels {curr['FeelsLikeC']}°C Humidity {curr['humidity']}%")
    for day in data['weather'][:days]:
        print(f"  {day['date']}: {day['maxtempC']}°/{day['mintempC']}°C "
              f"{day['hourly'][4]['weatherDesc'][0]['value']}")

if __name__ == "__main__":
    get_weather(sys.argv[1] if len(sys.argv)>1 else "Taipei")

總結建議

  • 互動式查看、美觀介面 → wego
  • 零依賴、腳本嵌入、單行摘要 → curl wttr.in
  • 自動化監控、圖形化狀態列 → wttr.in + Shell/Python
  • 離線環境 → 無解,需網路獲取氣象數據。
copyright © 萬盛學電腦網 all rights reserved