1. Create an Account on https://home.openweathermap.org/ and create your API key, save it into config.ini:
[openweathermap]
api=7383374766289c804cbf5a68ac704491
2. create get_weather.py
import configparser
import requests
import sys
def get_api_key():
config = configparser.ConfigParser()
config.read('config.ini')
return config['openweathermap']['api']
def get_weather(api_key, location):
url = "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}".format(location, api_key)
r = requests.get(url)
return r.json()
def main():
if len(sys.argv) != 2:
exit("Usage: {} LOCATION".format(sys.argv[0]))
location = sys.argv[1]
api_key = get_api_key()
weather = get_weather(api_key, location)
print(weather['main']['temp'])
print(weather)
if __name__ == '__main__':
main()
- test code:
C:\Users\zhuby\hans>python get_weather.py Toronto
20.2
{‘coord’: {‘lon’: -79.42, ‘lat’: 43.7}, ‘weather’: [{‘id’: 800, ‘main’: ‘Clear’, ‘description’: ‘clear sky’, ‘icon’: ’01d’}], ‘base’: ‘stations’, ‘main’: {‘temp’: 20.2, ‘feels_like’: 18.43, ‘temp_min’: 18, ‘temp_max’: 22.78, ‘pressure’: 1020, ‘humidity’: 52}, ‘visibility’: 14484, ‘wind’: {‘speed’: 2.6, ‘deg’: 100}, ‘clouds’: {‘all’: 1}, ‘dt’: 1591637542, ‘sys’: {‘type’: 1, ‘id’: 941, ‘country’: ‘CA’, ‘sunrise’: 1591608974, ‘sunset’: 1591664262}, ‘timezone’: -14400, ‘id’: 6167865, ‘name’: ‘Toronto’, ‘cod’: 200}