使用Windows 7一段时间,觉得它的自动换壁纸也挺好用的,换到Ubuntu 11.04上,本想装个软件让它自动换,后来发现Drapes运行不了,又懒得装其他软件了。
于是想按照别人说的写个shell自动换壁纸,但是因为偶没怎么接触过shell编程,所以就求助于Python了。
Ubuntu原本就可以支持自动换壁纸,我们在外观首选项下的背景项可以看到原本就有个宇宙的幻灯片。这个幻灯片主要靠xml定义,位于/usr/share/backgrounds/cosmos/下的background-1.xml,我们打开它可以看到:
2009
08
04
00
00
00
这个是设置幻灯片开始时间,只要设为过去或者现在就可以马上开始了。
于是下面就有很多类是这样的:
1795.0
/usr/share/backgrounds/cosmos/cloud.jpg
5.0
/usr/share/backgrounds/cosmos/cloud.jpg
/usr/share/backgrounds/cosmos/comet.jpg
1795.0
/usr/share/backgrounds/cosmos/comet.jpg
5.0
/usr/share/backgrounds/cosmos/comet.jpg
/usr/share/backgrounds/cosmos/earth-horizon.jpg
static标签下的duration是设置一张图保持多久,transition同理,两者加起来就是一张图显示的时间了,1795 + 5 = 1800秒,即 30 分钟。
然后如果要循环播放的话,最后一个transtion要跳回第一个即可。虽然我们可以手写这个xml,但是实在太恶心了。
所以我们求助于python自动生成了。
# -*-coding:utf-8-*-
# 作者:华亮
importos
xml ='''''
2009
08
04
00
00
00
'''
static_duration =1795# 一张壁纸的停留时间
trasition_duration =5# 切换时间www.linuxidc.com
defCreateStatic(duration, file):
return'\n\t'+ str(duration) +'\n\t'+ str(file) +'\n\n'
defCreateTransition(duration, fromFile, toFile):
return'\n\t'+ str(duration) +'\n\t'+ str(fromFile) +'\n\t'+ str(toFile) +'\n\n'
# 读取当前目录下所有文件
images = []
forfilenameinos.listdir(os.getcwd()):
root, ext = os.path.splitext(filename)
ifext.lower() =='.bmp'or'.jpg'or'.png':
images.append(os.path.join(os.getcwd(), filename))
# 生成XML
foriinrange(len(images) -1):
xml += CreateStatic(static_duration, images[i]) + CreateTransition(trasition_duration, images[i], images[i +1])
xml += CreateStatic(static_duration, images[len(images) -1]) + CreateTransition(trasition_duration, images[len(images) -1], images[0]) +''
# 保存文件
file = open(os.path.basename(os.getcwd()) +".xml",'w')
file.write(xml)
file.close()
将这个py文件放到图片的目录下,保存为back.py,然后在shell里运行:python back.py,随后会生成以这个目录命名的xml文件,我们就打开外观首选项,添加刚刚生成的xml即可。
自己动手,丰衣足食~