上星期看到這篇:如何将Bing的每日桌面图像变成我的Windows 7桌面,就順手試試看改用 Python 來作,執行這個 script 以後,會自動拿 bing 的圖片來作為你 GNOME 的桌面背景圖片。
目前只有一個小問題,就是 xml.dom.minidom 有時候會因為 & 的關係導致解析失敗。
#!/usr/bin/env python import random import os.path import subprocess import urllib2 import xml.dom.minidom from xml.dom.minidom import Node def get_xml(): response = urllib2.urlopen('http://feeds.feedburner.com/bingimages') xml = response.read() return xml def parse_and_get_first_image_uri( xml_str ): if xml_str=="": return "" doc=xml.dom.minidom.parseString( xml_str ) urls=[] for node in doc.getElementsByTagName("enclosure"): urls.append( node.getAttribute("url") ) index=random.randint( 0, len(urls)-1 ) if len(urls)>0: return urls[ index ] else: return "" def get_uri( uri, output ): response = urllib2.urlopen( uri ) image_file=open( output, 'w' ) image_file.write( response.read() ) image_file.close() return def set_wallpaper( filename ): args=[] args.append( 'gconftool-2' ) args.append( '/desktop/gnome/background/picture_filename' ) args.append( '--set' ) args.append( filename ) args.append( '--type=string' ) subprocess.call( args ) uri=parse_and_get_first_image_uri( get_xml() ) tmp_dir = os.path.join( *(os.path.expanduser("~"), "tmp") ) if uri!="": if not os.path.exists( tmp_dir ): os.mkdir( tmp_dir ) filename, extname = os.path.splitext( os.path.basename( uri ) ) image_filename=os.path.join( *( tmp_dir, "bing" + extname ) ) get_uri( uri, image_filename ) set_wallpaper( image_filename ) else: print "get nothing."