Tuesday, October 18, 2005

Update : I moved my code, and the enhancements that other people have provided in the comments to my coding page, along with files you can download.

I was looking for a simple wallpaper switcher for the Gnome desktop. All I needed was something that I could point to a folder full for wallpapers and it would automatically change my wallpaper periodically after every specified interval. It is quite puzzling why such an app did not exist.

I did find some applet down at [gnomefiles.org], but could not get it to work properly. Finally, I decided to get off my ass and do something about. After about an hour, I had a neat python script to change my Gnome desktop wallpaper every specified number of seconds.

Here is the help usage :

            deepak@vyomlaptop:~/python/wallpaperchanger$ ./changewallpaper -h
           usage: changewallpaper [options]

           options:
             -h, --help            show this help message and exit
             -f FOLDER, --folder=FOLDER
                                   use wallpapers from FOLDER
             -i INTERVAL, --interval=INTERVAL
                                   time interval in seconds

Here is python script. I did not put a license, but please feel free to do whatever you want with it.

            #!/usr/bin/python
           from optparse import OptionParser
           import os
           import sys, string, time
           import random

           def changeWallpaper(filename):
                   cmd = string.join(["gconftool -s /desktop/gnome/background/picture_filename -t string \"",filename,"\""],'')
                   os.system(cmd) # execute system command

           # Parse commandline arguments
           parser = OptionParser()
           parser.add_option("-f", "--folder", dest="folder",
                           help="use wallpapers from FOLDER", metavar="FOLDER")            parser.add_option("-i", "--interval",
                           type="float",
                           dest="interval", default=300, # default is change wallpaper every 5 mins
                           help="time interval in seconds", metavar="INTERVAL")
           (options, args) = parser.parse_args()

           # Validate for presence of valid folder
           if options.folder is None:
                   raise ValueError, "No valid folder specified"
           if not(os.path.isdir(options.folder)):
                   raise ValueError, "The folder specified is not valid"

           # Make list of images
           imagefilelist = [filename for filename in os.listdir(options.folder)
                           if (filename.lower().endswith("jpg")
                           or filename.lower().endswith("png")
                           or filename.lower().endswith("gif"))]
           imagefilelist = [string.join([os.path.normpath(options.folder),imgFile],"/") for imgFile in imagefilelist]

           # Validate for presence of images
           if (len(imagefilelist) == 0):
                   raise ValueError, "Folder does not contain any image files"

           count=0 #init index
           random.shuffle(imagefilelist) #randomize wallpaper order
           try:
                   while (True):
                           if (count < len(imagefilelist) -1):
                                   count = count + 1
                           else:
                                   count = 0
                           time.sleep(options.interval)
                           changeWallpaper(imagefilelist[count])
           except KeyboardInterrupt:
                   pass

I can already think of some improvements, but they will have to wait for some other time:

  • Convert into a Gnome panel applet and add a GUI for the options.
  • Take the wallpaper from the list of wallpapers used by the Gnome utility to change background.

Just add this script to your startup items, and you don't need to worry about launching it manually.

P.S. : Just realised that this blog has completed 50 posts!!

17 comments:

divya said...

YAY! 50 posts is AWESOME GOING! Congrats! Keep up the good work!

Anonymous said...

I got into the same problem, couldn't get a program that were supposed to do such a imple task to do it.
It required FAM and other silly things to do it, and were about 10 times the size of this script.
Great job!

Anonymous said...

This kicks ace. Nice hack.

Anonymous said...

Thanks for the post! I didn't use your script exactly but it gave me some good ideas. I found this post on using gconf directly from python. So now I use :
client.set_string('/desktop/gnome/background/picture_filename',filename)


cheers,
gerwin

Anonymous said...

Thanks for the post! I didn't use your script exactly but it gave me some good ideas. I found this post on using gconf directly from python. So now I use :

import gconf
client = gconf.client_get_default()
client.set_string('/desktop/gnome/background/picture_filename',filename)


cheers,
gerwin
ps. sorry for the doublepost

Anonymous said...

so im a newb, yeh its rue tbelieve it or not and i dunno what to do with this script. do i save it with no file extension? howdo i compile it?

lost soul looking for direction...

i just installed ubuntu edgdy eft and having fun trying out all this new stuff

Deepak said...

just copy paste the code into a file (for e.g switcher.py) and then run it using python

python switcher.py <arguments>

Anonymous said...

thanks for the quick reply!

so now i know how to compile in python

but i dont know how to program in it soo when i got this i didnt know what to do

File "wallpaperCHanger.py", line 2
from optparse import OptionParser
^
SyntaxError: invalid syntax

Thi-AIT said...

When I Save Change the configure blog. It appears the following sentence. Please help me solve it:
Thank you so much:
[Error:
name: SyntaxError
message: Statement on line 38: Syntax error in call to eval: line 1 :
求杯⼼㹡Ⱗ✠慤慴㨧笠氧祡畯⵴楴汴❥›䐧瑡⁡牁档癩❥絽㬩紊挠瑡档⠠⥥笠 椠⁦琨灹潥⁦潬⁧㴡✠湵敤楦敮❤
੻††潬⡧䠧湡汤䍥
---------------------------------------------------^
Backtrace:
Line 38 of linked script http://beta.blogger.com/widgets/3026280951-widget-config.js
c_y("Message (" + b + ") processing took " + new Date().getTime() - h + " ms");
c_y("Message (" + b + ") processing failed: " + f);
alert(f + "\n" + f.stack + "\n\n" + a.responseText);
throw f;
if (204 == g)
else
--c_Ra;
Line 39 of linked script http://beta.blogger.com/widgets/3026280951-widget-config.js
c_Fb(j, i, k, c);
At unknown location
[statement source code not available]

]
undefined

Anonymous said...

I don't really know if this will help anyone, since the post has been here for a while, since 2005, but maybe you get here casually just like me XD. An anonymous poster was asking for some help with error popping out wen trying to run the script. These errors are caused due to indentation, line jumps and spacing when copying and pasting. So all you need to do is check that the indentation (spacing at the beginning),jump lines and spacing from the file in which you paste is exactly the same as the you see it in your browser.
Note that you might not see the entire lines of code, just change the font size in the browser.
And when you put phyton name_of_file.py in the terminal, include the parameters. Ex. "python wallpaperchange.py -f /home/user/wallpapers/ -i 600"

good luck, and thanks for the script Deepak!!

Anonymous said...

I made some updates - in order to add more features, and better command line control.

For instance, this version has a default wallpaper you can fall back too when you kill the application, and allows you to select centered, scaled zoomed etc.

#! /usr/bin/env python

from optparse import OptionParser
import os
import sys, string, time
import random

def changeWallpaper(filename):
cmd = string.join(["gconftool -s /desktop/gnome/background/picture_filename -t string \"",filename,"\""],'')
os.system(cmd) # execute system command

# Parse commandline arguments
parser = OptionParser()
parser.add_option("-f", "--folder", dest="folder", help="use wallpapers from FOLDER", metavar="FOLDER")
parser.add_option("-i", "--interval", type="float", dest="interval", default=300, help="time interval in seconds", metavar="INTERVAL")
parser.add_option("-m", "--mode", type="string", dest="wallpaper_mode", default="centered", help="Wallpaper can be displayed in several modes: none, wallpaper, centered, scaled, stretched, zoom")
parser.add_option("-d", "--default", dest="default_image", help="specify default image when program is killed", metavar="FILENAME", default="nothing.gif")
parser.add_option("-c", "--bg-color-mode", dest="bg_color_mode", default="solid", help="Background Color Options: solid, hg (horizontal gradient, vg (vertical gradient)",metavar="COLOR_MODE")

(options, args) = parser.parse_args()

# Validate for presence of valid folder
if options.folder is None:
raise ValueError, "No valid folder specified"
if not(os.path.isdir(options.folder)):
raise ValueError, "The folder specified is not valid"

# Set Background Color Mode
if options.bg_color_mode == "vg":
cmd = "gconftool -s /desktop/gnome/background/color_shading_type -t string \"vertical-gradient\""
os.system(cmd) # execute system command

elif options.bg_color_mode == "hg":
cmd = "gconftool -s /desktop/gnome/background/color_shading_type -t string \"horizontal-gradient\""
os.system(cmd) # execute system command

else:
cmd = "gconftool -s /desktop/gnome/background/color_shading_type -t string \"solid\""
os.system(cmd) # execute system command




# Set wallpaper display mode
cmd = string.join(["gconftool -s /desktop/gnome/background/picture_options -t string \"", options.wallpaper_mode ,"\""],'')
os.system(cmd) # execute system command

# Make list of images
imagefilelist = [filename for filename in os.listdir(options.folder)
if (filename.lower().endswith("jpg")
or filename.lower().endswith("png")
or filename.lower().endswith("gif"))]
imagefilelist = [string.join([os.path.normpath(options.folder),imgFile],"/") for imgFile in imagefilelist]

# Validate for presence of images
if (len(imagefilelist) == 0):
raise ValueError, "Folder does not contain any image files"

count=0 #init index
random.shuffle(imagefilelist) #randomize wallpaper order
try:
while (True):
if (count < len(imagefilelist) -1):
count = count + 1
else:
count = 0
time.sleep(options.interval)
changeWallpaper(imagefilelist[count])


except KeyboardInterrupt:
print options.default_image
cmd = string.join(["gconftool -s /desktop/gnome/background/picture_filename -t string \"", options.default_image ,"\""],'')
os.system(cmd) # execute system command
pass

Erik said...

Thanks a lot; this is more or less exactly what I was looking for and due to my limited Python-skills couldn't have written on my own!

I did take the liberty of making some changes (to the updated version):
- changed gconftool to gconftool-2 (since I didn't have gconftool)
- Commented switching to default image on kill (I prefer to leave the last image on my desktop)
- Fixed (I think ... at least it works for me now ;-) ) actual shuffling code : previously it just counted all your wallpapers and displayed the first one in the shuffled list
- Added another random.shuffle when all images have been displayed. This should prevent repetitiveness in short lists
- Added --oneshot (-o) option. If given, the script will change your wallpaper once to a random one from the specified folder. This way it can be called in your session startup to give you a random wallpaper on login.

The edited version :

#! /usr/bin/env python

from optparse import OptionParser
import os
import sys, string, time
import random

def changeWallpaper(filename):
cmd = string.join(["gconftool-2 -s /desktop/gnome/background/picture_filename -t string \"",filename,"\""],'')
os.system(cmd) # execute system command

# Parse commandline arguments
parser = OptionParser()
parser.add_option("-f", "--folder", dest="folder", help="use wallpapers from FOLDER", metavar="FOLDER")
parser.add_option("-i", "--interval", type="float", dest="interval", default=300, help="time interval in seconds", metavar="INTERVAL")
parser.add_option("-m", "--mode", type="string", dest="wallpaper_mode", default="centered", help="Wallpaper can be displayed in several modes: none, wallpaper, centered, scaled, stretched, zoom")
parser.add_option("-d", "--default", dest="default_image", help="specify default image when program is killed", metavar="FILENAME", default="nothing.gif")
parser.add_option("-c", "--bg-color-mode", dest="bg_color_mode", default="solid", help="Background Color Options: solid, hg (horizontal gradient, vg (vertical gradient)",metavar="COLOR_MODE")
parser.add_option("-o", "--oneshot", nargs=0)

(options, args) = parser.parse_args()

# Validate for presence of valid folder
if options.folder is None:
raise ValueError, "No valid folder specified"
if not(os.path.isdir(options.folder)):
raise ValueError, "The folder specified is not valid"

# Set Background Color Mode
if options.bg_color_mode == "vg":
cmd = "gconftool-2 -s /desktop/gnome/background/color_shading_type -t string \"vertical-gradient\""
os.system(cmd) # execute system command

elif options.bg_color_mode == "hg":
cmd = "gconftool-2 -s /desktop/gnome/background/color_shading_type -t string \"horizontal-gradient\""
os.system(cmd) # execute system command

else:
cmd = "gconftool-2 -s /desktop/gnome/background/color_shading_type -t string \"solid\""
os.system(cmd) # execute system command

# Set wallpaper display mode
cmd = string.join(["gconftool-2 -s /desktop/gnome/background/picture_options -t string \"", options.wallpaper_mode ,"\""],'')
os.system(cmd) # execute system command

# Make list of images
imagefilelist = [filename for filename in os.listdir(options.folder)
if (filename.lower().endswith("jpg")
or filename.lower().endswith("png")
or filename.lower().endswith("gif"))]
imagefilelist = [string.join([os.path.normpath(options.folder),imgFile],"/") for imgFile in imagefilelist]

# Validate for presence of images
if (len(imagefilelist) == 0):
raise ValueError, "Folder does not contain any image files"

count=0 #init index
random.shuffle(imagefilelist) #randomize wallpaper order
try:
if options.oneshot is None:
while (True):
if (count <= len(imagefilelist) -1):
time.sleep(options.interval)
changeWallpaper(imagefilelist[count])
count = count + 1
else:
random.shuffle(imagefilelist)
count = 0
time.sleep(options.interval)
changeWallpaper(imagefilelist[count])
else:
changeWallpaper(imagefilelist[count])
except KeyboardInterrupt:
#print options.default_image
#cmd = string.join(["gconftool-2 -s /desktop/gnome/background/picture_filename -t string \"", options.default_image ,"\""],'')
#os.system(cmd) # execute system command
pass

nigel said...

Very Interesting

salase said...

This is a really usefull and simple code, thanks for it dude.

Nick Marinho ? said...

There's so man errors of indentation when I copy the content to a file and execute it.

Please help me.

Thanks a lot!

Deepak said...

Nick, can you download the code from http://deepak.jois.name/code

I updated the post on top to indicate that I have put up the code there.

This momentousdecree wow gold came as a great beacon gold in wow light of hope buy wow gold to millions of negroslaves wow gold kaufen who had been seared in the flames of withering injustice.maplestory mesos it came as a joyous daybreak to end the long night ofcaptivity.but one hundred years later,maplestory money we must face the tragic fact thatthe negro is still not free.maple money one hundred years later,sell wow gold the lifeof the negro is still sadly crippled by the manacles ofsegregation and the chains of discrimination. one hundred yearslater,maple story money the negro lives on a lonely island of poverty in themidst of a vast ocean of material prosperity.wow powerleveling one hundred yearslater,maple story power leveling the negro is still languishing in the corners of americansociety and finds himself an exile in his own land. so we havecome here today to dramatize wow powerleveln an appalling condition.in a ms mesos sense we have come to our nation''s capital to cash a check.when the architects of our republic wow powerleveln wrote the magnificent wordsof the constitution and the declaration of independence, theywere signing a promissory note maplestory power leveling to which every american was tofall heir.

Followers

About Me

My Photo
Deepak Jois
Visit my Status Page to know more about me
View my complete profile