This is a simple program that gets a forecast from the free API from wunderground, extracts and prints current forecast by zipcode.
Requires ElementTree from xml.etree, which may need to be installed
| #!/usr/bin/env python | |
| import sys | |
| import urllib2 | |
| from xml.etree import ElementTree as ET | |
| def getforecast(zipcode): | |
| """gets current forecast from wunderground""" | |
| url='http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query={}' | |
| forecastxml = urllib2.urlopen(url.format(zipcode)).read() | |
| fc = ET.fromstring(forecastxml) | |
| time_str = fc.find(".//txt_forecast//title") | |
| forecast_str = fc.find(".//txt_forecast//fcttext") | |
| return((time_str.text,forecast_str.text)) | |
| def main(zipcode): | |
| """get zip from argv and print""" | |
| print "Weather for {0}: {1}".format(*getforecast(zipcode)) | |
| # time_str.text,forecast_str.text) | |
| if __name__ == '__main__': | |
| default_zip = 48824 | |
| zipcode = default_zip | |
| if len(sys.argv) > 1: | |
| zipcode = sys.argv[1] | |
| main(zipcode) |