Friday 16 October 2009

Astronomy Picture of the Day (python)

Some code to set the astronomy picture of the day as your desktop background... have phun :-)



#!/usr/bin/env python
# Nasa's Astronomy Picture of the Day
# Desktop Background Changer (requires python 2.5)
# Written by: Jaco Wiese

# You are free to do whatever you wish with this code. Have phun!

# Save old picture to this location
# Make sure you created the directory with correct permissions

# For Windows you can add a scheduled task for each day
# and for Linux you can just dump the script in /etc/cron.daily

# Windows Location
# For Some odd reason windows requires the desktop size
SaveLocation = "apod"
width = 1024
height = 768

# Linux Location - Uncomment next line to use on linux
#SaveLocation = "/home/snowy/Apod/astropix"

# There seems to be no easy way to set the desktop background in windows
# You have to set desktop.html as your background
# If you know of a better solution, let me know!

# ---------------------------------------------------------

import urllib
import re
import os

ServerLink = "http://antwrp.gsfc.nasa.gov/apod/"

try:
htmldata = urllib.urlopen(ServerLink + "astropix.html").read()
except:
print "Cannot access internet."
exit(0)

b = re.search("", htmldata)
a = re.search("\".*\"", htmldata[b.start():b.end()])

if (a == None or b == None):
print "No picture available today."
exit(0)

FileLink = a.group().strip("\"");
FileName = SaveLocation + "/" + FileLink.split("/")[2];

if (not os.path.exists(SaveLocation)):
print "Please create directory: " + SaveLocation
exit(0)

try:
fileurl = urllib.urlopen(ServerLink + FileLink)
f = open(FileName, "wb")
f.write(fileurl.read())
f.close()
except:
print "Cannot Download or create File. Please check folder permissions."
exit(0)

# There seems to be no easy way to set the desktop background in windows
# You have to set desktop.html as your background
# If you know of a better solution, let me know!
if (os.name == "nt"):
hf = open("desktop.html", "wt")
hf.write("")
hf.write("")
hf.write(" ")
hf.write("")
hf.write("")
hf.write("")
hf.write("")
hf.write("")
hf.write("")
hf.close()
exit(0)

# Linux - Gnome (Currently not running kde)
if (os.name == "posix"):
os.system("gconftool-2 --type string --set /desktop/gnome/background/picture_filename " + FileName)
exit(0)


0 comments: