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']) + '%.' )

Configure OpenCV-Python development environment in Windows

In older days, it is relative complex to configure a OpenCV development environment. You have to install an IDE, e.g. Mircosoft Visual Studio, and have to set many configurations of the project, such as the include folder, the header folder and where the IDE can find the third-party OpenCV library. But after Python becomes one of the main streams, things has changed. Python has proven to be a better and easier way to program and test computer vision programs, compared with C++. In this article, I will show you the simple steps that could help you to configure an OpenCV-Python ready environment in Windows.

1. First, you have to download and install Python 2.7 and Numpy. Install them to their default locations, in order to avoid any further issues. The reason to use Python 2.7 instead of Python 3.x is that Python 2.7 is best supported by most third-party libraries, while Python 3 is too new for all the scientific libraries to be fully supported.

2. Download the latest OpenCV release from Sourceforge and extract it into a system folder, e.g., C:\Program Files\opencv.

3. Goto $(opencv folder)\build\python\2.7\x86 or \x64 based on your machine type. Copy cv2.pyd to $(python folder)\lib\site-packages.

That’s all you have to do. Really easy and will only cost you 10 minutes. Now let’s open the Python IDLE and test if the environment is working:

import numpy
import cv2

print cv2.__version__

Run the code and if you got the version printed and no error message, then congratulations: you have succeed. But if you did get error message, then you should check the version of both the Python and the OpenCV is correct. If you have multiple versions of Python, then check if you have run the right version of IDLE.

Before we try more complicated vision algorithms, let’s simply connect a USB camera first and try to get the video stream from the camera and display it on the screen:

import cv2

cap = cv2.VideoCapture(0)

while(True):
    _, frameInput = cap.read()
    cv2.imshow('camera', frameInput)

    if cv2.waitKey(33) == 27:
        break

cv2.destroyAllWindows()
cap.release()

What you should got is a pop-up window displaying the current image captured from the camera. You don’t have to understand this code at the moment, but the thing is once you got the live video stream from the USB camera, further steps can be done to process, modify and save it. More details and examples will be discussed later in my further blogs.

References
[1] OpenCV-Python Tutorials, Install OpenCV-Python in Windows, available at: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html

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,大功告成!