How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
You can call "defaults write com.apple.Desktop Background ..." as described in this article: http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/
The article also goes into scripting this to run automatically, but the first little bit should get you started.
You might also be interested in the defaults man pages: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html
From python, if you have appscript installed (sudo easy_install appscript
), you can simply do
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
Otherwise, this applescript will change the desktop background
tell application "Finder"
set desktop picture to POSIX file "/your/filename.jpg"
end tell
You can run it from the command line using osascript
, or from Python using something like
import subprocess
SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def set_desktop_background(filename):
subprocess.Popen(SCRIPT%filename, shell=True)
To add to Matt Miller's response: you can use subprocess.call() to execute a shell command as so:
import subprocess
subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...])
You could also use py-appscript instead of Popening osascript or use ScriptingBridge with pyobjc which is included in 10.5 but a bit more cumbersome to use.
If you are doing this for the current user, you can run, from a shell:
defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
Or, as root, for another user:
/usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist
You will of course want to replace the image filename and user name.
The new setting will take effect when the Dock starts up -- either at login, or, when you
killall Dock
[Based on a posting elsewhere, and based on information from Matt Miller's answer.]