Skip to content

Instantly share code, notes, and snippets.

@erikng
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikng/9143855 to your computer and use it in GitHub Desktop.
Save erikng/9143855 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
'''Uses Cocoa classes via PyObjC to set a desktop picture on all screens.
Modified script to read from com.apple.desktop via MCX
Tested on Mavericks.
See:
https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSWorkspace_Class/Reference/Reference.html
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html
https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSScreen_Class/Reference/Reference.html
http://docs.python.org/dev/library/plistlib.html
Based on conversations
http://derflounder.wordpress.com/2013/10/26/mavericks-desktop-background-picture-settings-moved-from-librarypreferencescom-apple-desktop-plist/
https://groups.google.com/forum/?fromgroups#!topic/macenterprise/zVDzyOwxJoM
Original script by Greg Neagle
Modified by Erik Gomez with guidance from Greg Neagle
'''
import os
import glob
import plistlib
import getpass
from AppKit import NSWorkspace, NSScreen
from Foundation import NSURL
from CoreFoundation import *
# Grab the full path from com.apple.desktop MC X value
''' Original idea did not work, but leaving it here.
pathtomcx = os.path.expanduser("/Library/Managed Preferences")
username = getpass.getuser()
pathtoplist = os.path.join(pathtomcx, username, 'com.apple.desktop.plist')
desktopwall = plistlib.readPlist (pathtoplist)
desktopwall_path = desktopwall["Background"]["default"]["ImageFilePath"]
'''
bundle_id = 'com.apple.desktop'
desktopwall = CFPreferencesCopyAppValue("Background", bundle_id)
desktopwall_path = desktopwall["default"]["ImageFilePath"]
'''pictures_glob = glob.glob("/Library/Desktop Pictures/*.jpg")
picture_path = random.choice(pictures_glob)
'''
# generate a fileURL for the desktop picture
file_url = NSURL.fileURLWithPath_(desktopwall_path)
# make image options dictionary
# we just make an empty one because the defaults are fine
options = {}
# get shared workspace
ws = NSWorkspace.sharedWorkspace()
# iterate over all screens
for screen in NSScreen.screens():
# tell the workspace to set the desktop picture
(result, error) = ws.setDesktopImageURL_forScreen_options_error_(
file_url, screen, options, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment