Files
opalfiles/.config/waybar/scripts/weather2.py
2024-07-23 09:25:57 -07:00

44 lines
1.1 KiB
Python
Executable File

#!/usr/bin/env python3
import requests
import sys
import re
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
def get_weather():
try:
response = requests.get("http://wttr.in/sea?format=1")
response.raise_for_status()
return response.text.strip()
except requests.exceptions.RequestException as e:
return f"Error: {e}"
def format_weather(weather):
try:
# print(f"Raw weather data: '{weather}'") # Debug print
match = re.match(r"(\D+)\s+(\+?[\d.]+)°F", weather)
if not match:
return "Error: Unexpected weather format"
icon = match.group(1).strip()
temp_f = round(float(match.group(2)))
temp_c = round(fahrenheit_to_celsius(temp_f))
return f"{icon} {temp_c}°C / {temp_f}°F"
except Exception as e:
return f"Error formatting weather data: {e}"
if __name__ == "__main__":
weather = get_weather()
if weather.startswith("Error"):
print(weather)
sys.exit(1)
else:
formatted_weather = format_weather(weather)
print(formatted_weather)