Skip to content

Instantly share code, notes, and snippets.

@TurplePurtle
Created August 9, 2012 04:38
Show Gist options
  • Save TurplePurtle/3301038 to your computer and use it in GitHub Desktop.
Save TurplePurtle/3301038 to your computer and use it in GitHub Desktop.
APOD Wallpaperer
import os
import urllib2
import re
import ctypes
from _winreg import *
def apod():
url = "http://apod.nasa.gov/apod/"
# Make folder to save images
dir = "apodimg"
if not os.path.exists(dir):
print "Creating image folder..."
os.makedirs(dir)
# Fetch image URL
print "Accessing %s..." % url
page = urllib2.urlopen(url).read()
print "Searching for image..."
img_url = re.search("[^\"' ]*.jpg", page)
# If image URL was not found
while not img_url or img_url.group(0).find("http://") > -1:
page = urllib2.urlopen(url + re.search("(?!/)ap[^\"' ]*.html(?=.*?><)", page).group(0)).read()
img_url = re.search("[^\"' ]*.jpg", page)
img_url = img_url.group(0)
# Download image
fpath = "/".join([dir, img_url.split("/")[-1]])
if os.path.exists(fpath):
print "A file with the same name already exists."
over = raw_input("Enter \"y\" or \"yes\" to overwrite: ").lower()
if over != "y" and over != "yes":
return
print "Downloading image..."
f = open(fpath, "wb")
f.write(urllib2.urlopen(url + img_url).read())
f.close()
# Set image as background
print "Setting image as background..."
key = OpenKey(HKEY_CURRENT_USER, "Control Panel\Desktop", 0, KEY_ALL_ACCESS)
SetValueEx(key, "WallpaperStyle", 0, REG_SZ, "6")
SetValueEx(key, "Wallpaper", 0, REG_SZ, os.path.abspath(fpath))
CloseKey(key)
ctypes.windll.user32.SystemParametersInfoA(20, 0, os.path.abspath(fpath), 0)
def attempt(n):
if n < 1:
return
try:
if urllib2.urlopen("http://google.com"):
apod()
except Exception:
print "Error. Retrying %d more time(s)." % (n - 1)
attempt(n - 1)
attempt(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment