Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 138 lines (109 sloc) 4.66 kB
#!/usr/bin/env python
from xml.dom.minidom import parseString
try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from sys import argv, exit, stderr, stdout
import os.path
import datetime
VERSION = '.01'
URL = 'http://www.aaronfoltz.com'
YAHOO_API_KEY = 'dj0yJmk9TEdTT09FNVp6MWlhJmQ9WVdrOVpsaGhVbEZTTmpJbWNHbzlOalUyT0RNMk1qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTkw'
WOEID_URL = 'http://where.yahooapis.com/v1/places.q({0})?'
YAHOO_API_URL = 'http://weather.yahooapis.com/forecastrss?'
def main():
try:
# Forecast option
if "-f" in argv[1]:
# See if there is a zip with the argument
try:
place = argv[2]
getForecast(place)
# If no zip is provided, get it from the geolocation service
except IndexError:
place = getPlace()
getForecast(place)
# Else there isn't an option there, it must be a zip code if anything
else:
try:
place = argv[1]
getCurrent(place)
# No arguments are provided, get the place from the geolocation service
except IndexError:
place = getPlace()
getCurrent(place)
except IndexError:
place = getPlace()
getCurrent(place)
def getCurrent(place):
woeid = getWOEID(place)
# Call to get the weather
api = YAHOO_API_URL + urlencode({'w': woeid})
dom = parseString(urlopen(api).read())
# Get the necessary DOM elements
location = dom.getElementsByTagName('yweather:location')[0]
currentConditions = dom.getElementsByTagName('yweather:condition')[0]
atmosphere = dom.getElementsByTagName('yweather:atmosphere')[0]
wind = dom.getElementsByTagName('yweather:wind')[0]
print
print('Location: %s, %s' % (location.getAttribute("city"), location.getAttribute("region")))
print('Condition: %s' % currentConditions.getAttribute("text"))
print('Temperature: %sF/%sC' % (currentConditions.getAttribute("temp"), fahToCel(currentConditions.getAttribute("temp"))))
print('Humidity: %s' % atmosphere.getAttribute('humidity') + "%")
print('Wind: %s mph %s' % (wind.getAttribute("speed"), degToCompass(wind.getAttribute("direction"))))
def getForecast(place):
woeid = getWOEID(place)
# Call to get the weather
api = YAHOO_API_URL + urlencode({'w': woeid})
dom = parseString(urlopen(api).read())
# Get the necessary DOM elements
forecasts = dom.getElementsByTagName('yweather:forecast')
print
# Print info for each forecast day
for day in forecasts:
print('Day: %s' % datetime.datetime.strptime(day.getAttribute('date'), '%d %b %Y').strftime('%A, %B %d, %Y'))
print('\tHigh: %sF/%sC' % (day.getAttribute("high"), fahToCel(day.getAttribute("high"))))
print('\tLow: %sF/%sC' % (day.getAttribute("low"), fahToCel(day.getAttribute("low"))))
print('\tCondition: %s' % day.getAttribute('text'))
# Retrives zip code if not entered
def getPlace():
import re
path = "%s/.cliweather" % os.getenv("HOME")
if os.path.exists(path):
try:
f = open(path, 'r')
return f.read()
except:
print "Could not load .cliweather"
# Get the geoip information
geoip = urlopen('http://api.ipinfodb.com/v3/ip-city/?key=29e619f84fd83f32c4987573a4ccc11fd59b268234aa50c1289230f1fff0dbd2').read()
# The returned value is perfectly fine
if re.match("OK;;", geoip):
# regex to get the zip code
expression = "OK;;([^;]+;){5}(\w+)"
result = re.search(expression, geoip)
# return the zip code from the returned data
return result.group(2)
# Make a call to Yahoo's API to get the WOEID given a zip code
def getWOEID(place):
# Make the call to the API to return the XML with WOEID
api = (WOEID_URL + urlencode({'appid': YAHOO_API_KEY})).format(place)
dom = parseString(urlopen(api).read())
# Return parsed WOEID
return dom.getElementsByTagName('woeid')[0].firstChild.data
# Convert Fah to Cel
def fahToCel(value):
return '{0:.0f}'.format((100.0/(212-32)) * (int(value) - 32))
# From http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
def degToCompass(num):
num = int(num)
val=int((num / 22.5) + .5)
arr=["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
return arr[(val % 16)]
if __name__ == "__main__":
main()
Jump to Line
Something went wrong with that request. Please try again.