Create a command-line tool that fetches weather information from a public API and…
- User
Create a command-line tool that fetches weather information from a public API and displays it to the user
Assistant
Create a command-line tool that fetches weather information from a public API and displays it to the user
The user wants a command-line tool to fetch weather information and display it.
I need to choose a public weather API. OpenWeatherMap is a very common, free (with a key), and reliable choice for this type of task.
I need to choose a programming language. Python is excellent for CLI tools due to its readability and the argparse/requests libraries.
Key features needed:
Step-by-step Plan:
requests library is needed.requests, argparse, sys).get_weather(city, api_key).argparse to handle command-line arguments.Drafting the Code (Mental or Scratchpad):
https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metricparser.add_argument('city'), parser.add_argument('--api-key') (or environment variable approach? Environment variable is safer/better practice, but passing it as an arg is easier for a standalone script example. I'll support both: arg or env var). Actually, for a simple tutorial-style script, an argument is explicit. Let's stick to arguments but mention the env var option.Writing the Code (Python):
import requests
import argparse
import sys
def get_weather(city, api_key):
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
'q': city,
'appid': api_key,
'units': 'metric' # Defaulting to metric for simplicity, could add flag
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status() # Check for HTTP errors
data = response.json()
# Parsing logic
city_name = data['name']
temp = data['main']['temp']
desc = data['weather'][0]['description']
print(f"Weather in {city_name}: {temp}°C, {desc}")
except requests.exceptions.HTTPError as err:
if response.status_code == 404:
print("City not found.")
elif response.status_code == 401:
print("Invalid API Key.")
else:
print(f"HTTP Error: {err}")
except Exception as e:
print(f"An error occurred: {e}")
# Argparse setup...
Refining the output: I should make the output look a bit nicer (ASCII art or just clean formatting). Let's stick to clean formatting. I will use Python because it's the standard for this kind of utility.
Detailed Implementation Plan:
pip install requestsweather.pySelf-Correction/Edge Cases:
argparse handles quotes, or the user must use quotes. The URL encoding handles spaces automatically via requests.Final Polish: Add comments to the code. Provide clear instructions on how to run it.
Let's write the solution.
requests, argparse, os (for env vars), sys(Self-Correction during drafting): OpenWeatherMap requires an API key. I cannot provide a "working" key because they get revoked or rate-limited instantly. I must explicitly tell the user to sign up.
Structure of the response:
It uses the OpenWeatherMap API (a widely used, free service) and the popular requests library to fetch data.
requests library. Install it via pip:
pip install requests
weather.py)Save the following code into a file named weather.py.
import requests
import argparse
import sys
def get_weather(city, api_key, unit):
# Base URL for OpenWeatherMap
base_url = "http://api.openweathermap.org/data/2.5/weather"
# Determine unit symbol and metric system
if unit == "f":
unit_system = "imperial"
symbol = "°F"
else:
unit_system = "metric"
symbol = "°C"
# Parameters for the API request
params = {
'q': city,
'appid': api_key,
'units': unit_system
}
try:
# Make the request
response = requests.get(base_url, params=params)
# Raise an error if the request failed (4xx or 5xx status codes)
response.raise_for_status()
# Parse JSON data
data = response.json()
# Extract relevant information
city_name = data['name']
country = data['sys']['country']
temp = data['main']['temp']
feels_like = data['main']['feels_like']
description = data['weather'][0]['description']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
# Display the results
print(f"\n--- Weather in {city_name}, {country} ---")
print(f"Condition: {description.capitalize()}")
print(f"Temperature: {temp}{symbol} (Feels like {feels_like}{symbol})")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} {'mph' if unit == 'f' else 'm/s'}")
print("-----------------------------------\n")
except requests.exceptions.HTTPError as http_err:
if response.status_code == 404:
print(f"Error: City '{city}' not found.")
elif response.status_code == 401:
print("Error: Invalid API Key.")
else:
print(f"HTTP Error: {http_err}")
except Exception as err:
print(f"An error occurred: {err}")
def main():
# Set up argument parsing
parser = argparse.ArgumentParser(description="A simple command-line weather tool.")
parser.add_argument(
'city',
type=str,
help="Name of the city (e.g., 'London' or 'New York,US')"
)
parser.add_argument(
'--key',
type=str,
required=True,
help="Your OpenWeatherMap API Key"
)
parser.add_argument(
'-u', '--unit',
type=str,
choices=['c', 'f'],
default='c',
help="Temperature unit: 'c' for Celsius (default), 'f' for Fahrenheit"
)
args = parser.parse_args()
get_weather(args.city, args.key, args.unit)
if __name__ == "__main__":
main()
Open your terminal or command prompt and run the script using the following syntax:
python weather.py "City Name" --key YOUR_ACTUAL_API_KEY
Examples:
Get weather for London in Celsius (Default):
python weather.py "London" --key abc123yourkeyhere
Get weather for New York in Fahrenheit:
python weather.py "New York" --key abc123yourkeyhere -u f
argparse: This library handles command-line arguments. It ensures the user provides a city name and an API key, and it automatically generates a help menu (try running python weather.py -h).requests: This sends the HTTP GET request to the OpenWeatherMap servers.try...except):
404 errors (City not found) specifically so the user gets a helpful message instead of a crash.401 errors (Invalid API Key).main['temp']) and description (weather[0]['description']).