diff --git a/Python/api/api.py b/Python/api/api.py index 65bd5e9..bb3c251 100644 --- a/Python/api/api.py +++ b/Python/api/api.py @@ -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 \ No newline at end of file diff --git a/Python/api/py.log b/Python/api/py.log deleted file mode 100644 index 1ae0817..0000000 --- a/Python/api/py.log +++ /dev/null @@ -1,3 +0,0 @@ -Enter city name: Weather at coordinates (50.87489555, 6.05938669638836): -Temperature: 11.28°C -Weather: scattered clouds diff --git a/Python/api/weather.log b/Python/api/weather.log new file mode 100644 index 0000000..e69de29