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