一个用NationalGeographic每日图片做桌面的脚本

阅读更多

自己写的. python.

一开始是在Windows上运行, windows比较烦就烦在作为桌面的图片还得是BMP的, 这样还得装个python的PIL库来转换. 而且设置也相对麻烦.

最近在公司的另一台机器是ubuntu, 而在gnome上不仅可以直接用jpg文件, 设置也是一行命令就搞掂. 方便.

 

"""
Set the wallpaper as the picture got from national geographic picture of the day
by [email protected]
FIXME: Needs to set the registry to keep the wallpaper setting after restart system
"""
import ctypes
import calendar
import urllib
import socket
import os
import time

STOREDIR = os.path.expanduser("~") + '/wallpaper/pod/'
DOWNLOADED = 0

def setWallPaper(imagePath):
    if os.name=="nt":
        """Given a path to an image, convert it to bmp and set it as wallpaper"""
        bmpImage = Image.open(imagePath)
        newPath = STOREDIR + 'mywallpaper.bmp'
        bmpImage.save(newPath, "BMP")
        setWallpaperFromBMP(newPath)
    elif os.name=="posix":
        try:
            os.system("gconftool-2 -t string -s /desktop/gnome/background/picture_filename \""+imagePath+"\" -s /desktop/gnome/background/picture_options stretched")
        except:
            os.system("dcop kdesktop KBackgroundIface setWallpaper \""+imagePath+"\" 7")
def getPicture():
    try:
        sock = urllib.urlopen("http://lava.nationalgeographic.com/cgi-bin/pod/PhotoOfTheDay.cgi")
        htmlSource = sock.read()
        sock.close()   
        pos1 = htmlSource.find('Enlarge</a>')
        pos2 = htmlSource.find('Wallpaper</a>')
        page2 = htmlSource[pos1+50:pos2-2]
        pageurl = 'http://photography.nationalgeographic.com'+page2
        print pageurl
        sock = urllib.urlopen(pageurl)
        htmlSource = sock.read()
        sock.close()   
        pos1 = htmlSource.find('art-icon-wallpaper-1280.gif')
        pos2 = htmlSource.find('1280 x 1024 pixels')
        filename = htmlSource[pos1+42:pos2-2]
        print filename
        fileurl = 'http://photography.nationalgeographic.com'+filename
        onlyfile = filename[filename.rfind("/")+1:];
        print onlyfile
        fname = STOREDIR + onlyfile
        if not os.path.exists(fname):
            print 'file not retrieved'
            urllib.urlretrieve(fileurl, fname)
            print 'got the picture from ' + fileurl
        else:
            print 'The file is retrieved'
        return fname
    except Error:
        print "fail to getting picture of ",yy,mm,dd
        pass
    return fname

def setWallpaperOfToday():
    #filename  = getPicture()
    filename  = getPicture()
    print 'the filename is ' + filename
    setWallPaper(filename)

def setWallpaperByDate(yy,mm,dd):
    filename  = getPictureByDate(yy,mm,dd)
    setWallPaper(filename)

def prepare():
    #prepare the directory
    if not os.path.exists(STOREDIR):
        print 'going to make dir ' + STOREDIR
        os.makedirs(STOREDIR)
    print 'prepare done ...'

prepare()
setWallpaperOfToday()

print 'Wallpaper set ok!'

你可能感兴趣的:(脚本,OS,Python,Ubuntu,CGI)