Time pass by

Sunshine and rain of a developer

Posts Tagged ‘getopt’

Python Weather Forecast Wallpaper

Posted by vanguard33 on November 7, 2008

This code downloads yahoo xml weather forecast data and draws it on north east side of a picture
you can create a script like this

#!/bin/bash
sleep 25 && /home/hide1713/python_project/get_weather.py -c -i
/home/hide1713/Pictures/lamp.jpg -z 47408

then use chmod +x to make it executable, add this script in your start session.

It will create a new picture “pciture_name_new”, use this picture as your wallpaper.
NOTE: This script need lxml packet.

#!/usr/bin/env python
"""
Weather Forecast to wallpaper
By Lei Chen (hide1713 at gmail dot com)
This program reads xml data from yahoo then uses convert command to write a string on wallpaper
"""
from lxml import etree
import urllib2,os,getopt,sys
picture_name=''
zipcode=''
f_or_c='c'
args=sys.argv[1:]
def usage ():
    """"""
    print """Weather Forecast Wallpaper:
Usage:
-i <wallpaper file name>
-[f|c] : Fahrenheit/Celius
-z     : Your zipcode
"""

try:
    opts,args=getopt.getopt(args,'z:fci:')
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)
for o,a in opts:
    if o=="-c":
       f_or_c='c'
    if o=='-f':
       f_or_c='f'
    if o=="-i":
       picture_name=a
    if o=='-z':
        try:
            zipcode=int(a)
        except:
            print "zip code must be a number"
            sys.exit(2)

if not os.access(picture_name,os.W_OK):
   print "Can not write picture"
   usage()
   sys.exit(1)

if zipcode=='':
   print "No zipcode?"
   sys.exit(1)

print "Generating ",zipcode," weather forecast to ",picture_name
req=urllib2.Request("http://weather.yahooapis.com/forecastrss?p=%d&u=%s"%(zipcode,f_or_c))
fd = urllib2.urlopen(req)

tree=etree.fromstring(fd.read(),base_url="http://weather.yahooapis.com/forecastrss?p=47408")
s=''
for ele in tree.iter():
    if ele.tag=='{http://xml.weather.yahoo.com/ns/rss/1.0}forecast':
        s+=ele.attrib['day']+" "+ele.attrib['low']+"-"+ele.attrib['high']
        s+=" "+ele.attrib['text']+" "
os.popen("""convert %s  -pointsize 24 -draw "gravity NorthEast fill white text 0,12'%s'" %s"""%(picture_name,s,picture_name[:-4]+"_new"+picture_name[-4:]))

Posted in Python | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.