Created
April 9, 2011 11:21
-
-
Save mattijs/911319 to your computer and use it in GitHub Desktop.
Change the Gnome desktop background to a random image from a directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() | |
# 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(args.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