Get Weather from the commandline

This is a program written in python that gets the weather from the command line.

The usage is like:

$ 83204
5-day Forcast for  83206
       Monday Tuesday Wednesday Thursday Friday
High:  74       68       47       49       58
Low:   43       34       29       27       32

It breaks occasionally, most likely because wunderground’s output isn’t consistant.  but the whole point of this program is to figure out urllib and urllib2 to the networking class, so it’s no big deal to me.

Here’s the code:

#!/usr/bin/env python

This is the most useful program ever
Because it tells you all about the weather

I'm a poet
and I didn't
even realize
that I was one

Actually, this program is at the mercy of wunderground's output,
so it can break very very easily - but seemed to work for me in
the handfull of cases I tried it on.  The point is to demonstrate urllib
to my network class

import sys, re, urllib2, urllib

def numError():
   """Exits with a usage note"""
   print "Usage: weather zipcode"

def addGETdata(url, data):
   """Adds the get data to the url.  data should be a tuple"""
   return url + '?' + urllib.urlencode(data)

def printToScreen(areacode, high, low, days):
   print "5-day Forcast for ", areacode, "\n---------------------"
   print "      ",
   for i in days:
     print i,
   print ''
   print 'High: ',
   for i in high:
      print i,"     ",
   print ''
   print 'Low:  ',
   for i in low:
     print i,"     ",
   print ''

#Check that the user passes a 5-digit zip
  zip = int(sys.argv[1])

if (len(sys.argv[1]) != 5):

#make the get request
fullurl = addGETdata("", [("query",sys.argv[1])])
req = urllib2.Request(fullurl)
fd = urllib2.urlopen(req)

high = []
low = []
days = []

while 1:
   data =
   if not len(data):

   """this is not efficient, but works
      and in reality, the bottleneck is fetching the website"""

   #find what the next 5 days are
   m = re.findall('<td class="taC" style="width: 20%;">.*y', data)
   for i in m:
     #append the days
     days.append(i.rsplit('<td class="taC" style="width: 20%;">')[1])

   #find the high for the next five days
   m = re.findall('<span style="color: #900;">.*F', data)
   for i in m:
     #append only the integers of the weather
     high.append(i.rsplit('<span style="color: #900;">')[1].rstrip("&deg; F"))

   #find the lows for the next five days
   m = re.findall('<span style="color: #009;">.*F', data)
   for i in m:
     #append only the integers of the weather
     low.append(i.rsplit('<span style="color: #009;">')[1].rstrip("&deg; F"))

printToScreen(sys.argv[1], high, low, days)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: