在ubuntu中cosmos动态壁纸的python实现脚本

在ubuntu10.04下cosmos的动态壁纸效果和ms的theme差不多。

系统默认的cosmos在/usr/shared/background下的xml配置。

直接编辑的话,图片太多的话,记不住也容易写错。

为了复习python,于是写了一个脚本。

在当前文件夹下,预先存放若干图片,类型是jpg的。


    

然后执行以下脚本。(请保存为abc.py,然后在shell中python abc.py执行,如果顺利,应该会产生bk.xml)


#coding=gbk
import sys
import os
import string
import shutil
import xml.etree.ElementTree as xml

def insertxmlEl(elParent,elName,elValue):
    el = xml.Element(elName)
    el.text = elValue
    elParent.append(el)
    
def insertstaticEl(elParent,filename):
    elStatic = xml.Element('static')
    insertxmlEl(elStatic,'duration','1795')
    insertxmlEl(elStatic,'file',filename)
    elParent.append(elStatic)
    
def inserttransEl(elParent,fromFile,toFile):
    elTrans = xml.Element('transition')
    insertxmlEl(elTrans,'duration','5')
    insertxmlEl(elTrans,'from',fromFile)
    insertxmlEl(elTrans,'to',toFile)
    elParent.append(elTrans)
    
def cosmmaker(path,filename):
    root = xml.Element('background')
    elStarttime = xml.Element('starttime')
    insertxmlEl(elStarttime,'year','2009')
    insertxmlEl(elStarttime,'month','08')
    insertxmlEl(elStarttime,'day','04')
    insertxmlEl(elStarttime,'month','00')
    insertxmlEl(elStarttime,'minute','00')
    insertxmlEl(elStarttime,'second','00')
    root.append(elStarttime)
    
    firstFile = ''
    prevfile = ''
    #枚举文件
    for fileitem in os.listdir(path):        
        if(os.path.isfile(fileitem) == False):
            continue;
        filebasename , fext = os.path.splitext(fileitem);
        #检查是否是jpg文件
        if(string.lower(fext) != ".jpg"):
            continue;
        #如果文件名包含空格,就替换给下划线,然后重命名
        if(string.find(filebasename," ")):                    
            newfilename = string.replace(filebasename," ","_") + ".jpg"
            targetfile = os.path.join(path,newfilename)
            if(os.path.exists(targetfile) == False):
                os.rename(os.path.join(path,fileitem),targetfile)
        else:
            newfilename = filebasename + ".jpg"
            targetfile = os.path.join(path,newfilename)
           
        insertstaticEl(root,targetfile)
        if(firstFile == ''):
            firstFile = targetfile
        if(prevfile == ''):
            prevfile = targetfile
        else:
            inserttransEl(root,prevfile,targetfile)
        
    if(firstFile !=''):
        inserttransEl(root,targetfile,firstFile)
        
            
       
    #Open a file
    file = open(filename, 'w+')
    #Create an ElementTree object from the root element
    xml.ElementTree(root).write(file)
    #Close the file like a good programmer
    file.close()       
                
         

cosmmaker(os.getcwd()  ,"bk.xml")        
    
        
    

     

最后更换壁纸,加入刚才生成的bk.xml。

于是属于我们自己的cosmos壁纸就有了。

 

posted on 2012-06-21 10:12  febwave  阅读(397)  评论(0编辑  收藏  举报

导航