This Python script fetches current weather data for a specified city from wttr.in, converts the temperature to Fahrenheit, and displays the weather condition along with humidity. It provides a quick and API-key-free way to get up-to-date weather information right from your command line.
Click to view script…
#!/usr/bin/env python3
import requests
def get_weather(city):
url = f"http://wttr.in/{city}?format=j1"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
# Extract current weather information
current = data['current_condition'][0]
temp_c = float(current.get('temp_C', 0))
temp_f = (temp_c * 9/5) + 32 # Convert Celsius to Fahrenheit
weather_desc = current.get('weatherDesc', [{}])[0].get('value', 'No description')
humidity = current.get('humidity')
print(f"\nWeather in {city.title()}:")
print(f" Temperature: {temp_f:.1f}°F")
print(f" Condition: {weather_desc}")
print(f" Humidity: {humidity}%")
except requests.exceptions.RequestException as e:
print("Error: Could not retrieve weather data.")
print(e)
if __name__ == "__main__":
city = input("Enter a city name: ")
get_weather(city)