Tag Archives: Python

Py | Weather Report and Forecasting with Python

OpenWeatherMap.org is a free weather forecast website, where you can get up-to-date weather reports. One nice thing about this website is that it does provide weather APIs which you can use to fetch current weather data, and use them to build your own weather-forecasting program. In this post, I will describe how to use python to access the weather APIs and fetch the current weather information.

The full documentation of the APIs can be find here: http://openweathermap.org/api. To access the APIs, you have to register a new account to obtain an API key. There are two categories of APIs that can be used for free: Current and 5 day forecast. The Current API provides up-to-date weather data, which includes current temperature, humidity, wind, etc. The 5 day forecast gives information of the weather data for the next 5 days in every 3 hours. So you will get 40 forecasts in total. The usage of the APIs is simple, just send request to specific URLs, and get data in return given in the form of json or XML.

Here I give an example of how to use the Current API:

a) Fetch data from the URL provided by the document:

# this is where you should put your OpenWeatherMap API key
# get your own key from http://openweathermap.org/
API_KEY = "5eb19937b8ba9aa2029fe7e290b8d799"

# this is the city you want to enquiry
CITY_NAME = "York,uk"

# get weather data from weather.com
try:
	f = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=' \
                    + CITY_NAME + '&units=metric' + '&APPID=' +  API_KEY)
	respond_raw = f.read()
except:
        print 'Execption: URL is not correct!'
        raise

b) The default data format is json, we can unpack it with the json library:

# unpack json package into python dictionary
weather_dict = json.loads(respond_raw)

# print raw data with pprint
pp.pprint(weather_dict)

what you will get is something like this:

{   u'base': u'cmc stations',
    u'clouds': {   u'all': 36},
    u'cod': 200,
    u'coord': {   u'lat': 53.96, u'lon': -1.08},
    u'dt': 1447431162,
    u'id': 2633352,
    u'main': {   u'grnd_level': 1016.58,
                 u'humidity': 89,
                 u'pressure': 1016.58,
                 u'sea_level': 1027.66,
                 u'temp': 6.99,
                 u'temp_max': 6.99,
                 u'temp_min': 6.99},
    u'name': u'York',
    u'sys': {   u'country': u'GB',
                u'message': 0.0106,
                u'sunrise': 1447399715,
                u'sunset': 1447430881},
    u'weather': [   {   u'description': u'scattered clouds',
                        u'icon': u'03n',
                        u'id': 802,
                        u'main': u'Clouds'}],
    u'wind': {   u'deg': 257.001, u'speed': 10.62}}

c) Once you have the data stored in a python dictionary, you can generate something more readable and customized:

# print human-readable weather message
print('\n\n' + weather_dict['name'] + ' is ' + \
      weather_dict['weather'][0]['description'] + \
      ', temperature: ' + str(weather_dict['main']['temp']) + \
      ', humidity: ' + str(weather_dict['main']['humidity']) + '%.' )

which produces:

York is scattered clouds, temperature: 6.99, humidity: 89%.

Accessing 5 days forecast is very similar. But personally I think that API is not very useful, because it packs every 3 hour weather data in a single entity. This means in order to give a day-wide forecast, you have to process the data a little bit (day info is consisted of 8 entities) to find out the maximum and minimum temperatures. Also if you get more than one forecasts spreading in different times of the day (e.g., sunshine between 13:00-18:00 but raining between 10:00-13:00), you have to consider how to fairly describe the weather on that particular day . Due to these issues, I didn’t spent more efforts on that but instead switch to other weather providers. If you are more interested in forecasting, just have a try and let me know if it works.

Appendix. Full Python Code

weather_from_openweather.py

#!/usr/bin/python

import os
import urllib2 
import json
import pprint

pp = pprint.PrettyPrinter(indent=4)

# this is where you should put your OpenWeatherMap API key
# get your own key from http://openweathermap.org/
API_KEY = "5eb19937b8ba9aa2029fe7e290b8d799"

# this is the city you want to enquiry
CITY_NAME = "York,uk"

# get weather data from weather.com
try:
	f = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=' \
                    + CITY_NAME + '&units=metric' + '&APPID=' +  API_KEY)
	respond_raw = f.read()
except:
        print 'Execption: URL is not correct!'
        raise

# unpack json package into python dictionary
weather_dict = json.loads(respond_raw)

# print raw data with pprint
pp.pprint(weather_dict)

# print human-readable weather message
print('\n\n' + weather_dict['name'] + ' is ' + \
      weather_dict['weather'][0]['description'] + \
      ', temperature: ' + str(weather_dict['main']['temp']) + \
      ', humidity: ' + str(weather_dict['main']['humidity']) + '%.' )

Py | 用Python实现开机延迟启动脚本

最近电脑的开机速度越来越慢了,于是我打算通过延迟启动的方法提高系统的开机速度。

整体思路是:通过一个启动脚本,将开机不需要立刻启动的程序延缓启动,从而减轻系统开机时的压力。

使用Python脚本可以很容易的实现以上功能:

import os
os.system('sleep 30')
os.system('D:\iTools\EssentialPIMPort5\EssentialPIM.exe')

os.system('sleep 30')
os.system('D:\Program Files\Foxmail 7.0\Foxmail.exe')

os.system()函数可以通过调用系统命令行,实现其他程序的调用。

sleep 30是windows的dos命令,实现30秒的开机延时。

但是以上程序存在一个问题,就是只有上一个os.system()语句结束之后,下一条语句才会得到执行。这就导致了我只有关闭第一个启动的程序,才能启动下一个程序。

我在网上找到了解决方法,使用start “” “程序所在目录”,即可以实现非阻塞调用:

import os
os.system('sleep 30')
os.system('start "" "D:\iTools\EssentialPIMPort5\EssentialPIM.exe"')

os.system('sleep 30')
os.system('start "" "D:\Program Files\Foxmail 7.0\Foxmail.exe"')

最后一个问题是,我只有工作日才需要接收邮件,所以周末没有必要启动Foxmail程序,通过time模块获得今天是周几,之后再用一条if语句根据情况启动Foxmail:

import os
import time
import datetime

# what day is it today?
weekday = int(time.strftime("%w"))

# start essentialPIM
os.system('sleep 30')
os.system('start "" "D:\iTools\EssentialPIMPort5\EssentialPIM.exe"')

# start foxmail if is not weekend
if (weekday < 6):
    os.system('sleep 30')
    os.system('start "" "D:\Program Files\Foxmail 7.0\Foxmail.exe"')

最后一步,将这个脚本加入开机启动项,ok,大功告成!