Refactor weather API logging and enhance output with city name

This commit is contained in:
vista-man
2025-01-27 20:43:57 +01:00
parent 5fd81c8920
commit 15bffc0674
3 changed files with 10 additions and 7 deletions

View File

@@ -1,6 +1,7 @@
import requests
import time
import sys
import os
# Class to handle logging to multiple files
class Tee:
@@ -48,7 +49,7 @@ def get_coordinates(city_name):
return None, None
# Function to get the weather data for given coordinates using OpenWeatherMap API
def get_weather(lat, lon):
def get_weather(lat, lon, city_name):
api_key = 'cf2b92cba5cdb89baccb2fe05cacb3a5' # API key for OpenWeatherMap
base_url = 'https://api.openweathermap.org/data/2.5/weather' # Base URL for weather API
params = {
@@ -63,7 +64,7 @@ def get_weather(lat, lon):
if response.status_code == 200:
data = response.json() # Parse the JSON response
# Print the weather information
print(f"Weather at coordinates ({lat}, {lon}):")
print(f"Weather at coordinates ({lat}, {lon}) for city {city_name}:")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Weather: {data['weather'][0]['description']}")
else:
@@ -72,13 +73,18 @@ def get_weather(lat, lon):
# Main function to get city name input from the user and fetch weather data
if __name__ == "__main__":
with open('py.log', 'w') as log_file:
log_file_path = os.path.join(os.path.dirname(__file__), 'weather.log')
if os.path.exists(log_file_path):
with open(log_file_path, 'a') as log_file:
log_file.write('\n\n') # Add 2 empty lines before appending new logs
with open(log_file_path, 'a') as log_file:
tee = Tee(sys.stdout, log_file)
sys.stdout = tee
city_name = input("Enter city name: ") # Prompt the user to enter a city name
lat, lon = get_coordinates(city_name) # Get the coordinates of the city
if lat is not None and lon is not None:
get_weather(lat, lon) # Get the weather data for the coordinates
print(f"Coordinates for {city_name}: ({lat}, {lon})") # Log the coordinates and city name
get_weather(lat, lon, city_name) # Get the weather data for the coordinates
# Sleep for 5 seconds before exiting to ensure all logs are written
time.sleep(5)
tee.close() # Close the Tee object to ensure all files are properly closed