|
| 1 | +import argparse |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | +WEATHER_EMOJIS = { |
| 6 | + "clear": "☀️", |
| 7 | + "sunny": "☀️", |
| 8 | + "cloudy": "☁️", |
| 9 | + "partly cloudy": "⛅", |
| 10 | + "rain": "🌧️", |
| 11 | + "light rain": "🌦️", |
| 12 | + "heavy rain": "🌊", |
| 13 | + "storm": "🌩️", |
| 14 | + "snow": "❄️", |
| 15 | + "fog": "🌫️", |
| 16 | + "mist": "🌫️", |
| 17 | + "default": "🌍", |
| 18 | +} |
| 19 | + |
| 20 | +API_QUERY_TEMPLATE = "https://wttr.in/{city}?format=%C+%t" |
| 21 | + |
| 22 | + |
| 23 | +def get_weather_emoji(condition, weather_emojis=WEATHER_EMOJIS): |
| 24 | + condition = condition.lower() |
| 25 | + for key, emoji in weather_emojis.items(): |
| 26 | + if key in condition: |
| 27 | + return emoji |
| 28 | + return weather_emojis["default"] |
| 29 | + |
| 30 | + |
| 31 | +def get_weather(city, api_query_template=API_QUERY_TEMPLATE): |
| 32 | + api_query = api_query_template.format(city=city) |
| 33 | + try: |
| 34 | + response = requests.get(api_query) |
| 35 | + response.raise_for_status() |
| 36 | + weather_info = response.text.strip().split("+") |
| 37 | + if len(weather_info) < 2: |
| 38 | + return "Error: Unexpected weather data format." |
| 39 | + condition = weather_info[0].strip() |
| 40 | + temperature = weather_info[1].strip() |
| 41 | + emoji = get_weather_emoji(condition) |
| 42 | + return f"{emoji} {condition} -> {temperature}" |
| 43 | + except requests.RequestException: |
| 44 | + return "Error: Could not retrieve weather data." |
| 45 | + |
| 46 | + |
| 47 | +def parse_cli_args(): |
| 48 | + parser = argparse.ArgumentParser( |
| 49 | + prog="weather", |
| 50 | + description="Weather information for the specified city.", |
| 51 | + epilog="Thanks for using %(prog)s! :)", |
| 52 | + ) |
| 53 | + parser.add_argument( |
| 54 | + "city", |
| 55 | + nargs="+", |
| 56 | + help="Name of the city to get weather information for", |
| 57 | + ) |
| 58 | + parser.add_argument( |
| 59 | + "--version", |
| 60 | + action="version", |
| 61 | + version="%(prog)s 0.1.0", |
| 62 | + ) |
| 63 | + return parser.parse_args() |
| 64 | + |
| 65 | + |
| 66 | +def main(): |
| 67 | + args = parse_cli_args() |
| 68 | + weather = get_weather(" ".join(args.city)) |
| 69 | + print(weather) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments