Skip to content

Instantly share code, notes, and snippets.

@mattijs
Created April 9, 2011 13:11
Show Gist options
  • Save mattijs/911391 to your computer and use it in GitHub Desktop.
Save mattijs/911391 to your computer and use it in GitHub Desktop.
Change the Gnome desktop background to a random image from a directory
#!/usr/bin/env python
# This script will change the desktop background to a
# random image taken from a directory
#
# Use random_background.py --help for options
#
# Author: Mattijs Hoitink <mattijs@monkeyandmachine.com>
# License: none (public domain)
import sys, argparse, os, mimetypes, re, random, gconf
# Simple argument parsing
parser = argparse.ArgumentParser(description="Change Gnome desktop background to a random image from a directory")
parser.add_argument('--no-recurse', help='If files should not be searched recursively', dest='recursive', action='store_false', required=False)
parser.add_argument('path', action='store', help='Path to the directory to select a wallpaper from')
args = parser.parse_args()
# Check if the path exists
abs_path = os.path.abspath(args.path)
if not os.path.exists(abs_path):
print "Path '%s' does not exist" % abs_path
sys.exit(1)
# Find files in a directory recursively (or not)
def find_files(root, recursive = True):
found = []
for root, dirs, files in os.walk(root):
# Append files that are images
for file in files:
# Get the file path and mimetype
filePath = os.path.join(root, file)
fileMimetype = mimetypes.guess_type(filePath)[0]
# Check if the found file is an image
imageRegex = re.compile(r'image/[\w\-\.]*', re.IGNORECASE)
if fileMimetype and imageRegex.match(fileMimetype):
found.append(filePath)
# Check if we need to recurse intor sub-directories
if recursive:
for dir in dirs:
found += find_files(os.path.join(root, dir), recursive)
return found
# Fetch all wallpapers from the directory
backgrounds = find_files(abs_path, args.recursive)
if 0 >= len(backgrounds):
print "No background images were found"
sys.exit(0)
# Modify the background using GConf
gconf_background_path = '/desktop/gnome/background/picture_filename'
client = gconf.client_get_default()
new_background = backgrounds[random.randint(0, len(backgrounds) - 1)]
client.set_string(gconf_background_path, new_background)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment