[Tutor] Handy little xplanet script

Tim Wilson wilson@isis.visi.com
Tue, 19 Feb 2002 23:02:21 -0600 (CST)


Hey everyone,

I thought I'd share a little script I wrote. Other than the time it took
poking around in the time module's documentation, it didn't take long at
all and demonstrates a very practical and cool little use of Python.

I've been playing with xplanet lately, a very cool app that take an
image of the Earth and displays it as the background of your window
manager. It looks like there's a version that works with Windows, but I
haven't tried it. I run Linux on my workstation. Anyway, more info and
some really cool looking screenshots of xplanet in action can be found
at http://xplanet.sourceforge.net/

The author of xplanet produces a jpeg image every three hours taken from
satellite maps that show the actual cloud cover over the globe.
Very cool! I wanted to have my computer check periodically to make sure
I had the latest cloud image (I use cron to check every half hour) and
if not to download it so xplanet would use it the next time it refreshed
(every 10 minutes on my machine).

Sorry about the lengthy intro. :-) Here's the script:

--snip--
#!/usr/bin/env python

import urllib2, time, os

def retrieve(file, url):
    try:
        image = urllib2.urlopen(url).read()
        f = open(file, 'w')
        f.write(image)
        f.close()
    except HTTPError:  # HTTP 404 error
        pass  # Give up and try again later

CLOUD_FILE = '/home/wilson/tmp/clouds_2000.jpg'

# Check the Last-Modified header and turn it into
# a time tuple (in GMT).
url = 'http://xplanet.sourceforge.net/clouds_2000.jpg'
headers = urllib2.urlopen(url).info()  # Returns dictionary-like object
lastModified = headers['Last-Modified']
lm = time.strptime(lastModified, '%a, %d %b %Y %H:%M:%S GMT')

# Find out when the local clouds file was last modified and see
# which version is most recent.
try:
    stats = os.stat(CLOUD_FILE)
    st_ctime = stats[9]
    creationDate = time.gmtime(st_ctime)
    if lm > creationDate:
        retrieve(CLOUD_FILE, url)
except OSError:  # File doesn't exist
    retrieve(CLOUD_FILE, url)

--snip--

Have fun.

-Tim

--
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com