n8felton
10/13/2013 - 10:50 AM

set_desktop_bg.py

#!/usr/bin/python

# https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSWorkspace_Class/Reference/Reference.html#//apple_ref/doc/uid/20000391-BCIEBDGB
# 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#//apple_ref/doc/c_ref/NSScreen

from AppKit import NSWorkspace, NSScreen
from AppKit import NSWorkspaceDesktopImageScalingKey
from AppKit import NSImageScaleProportionallyUpOrDown
from AppKit import NSWorkspaceDesktopImageAllowClippingKey
from Foundation import NSURL
import optparse

p = optparse.OptionParser()
p.set_usage("""Usage: %prog [options]""")
p.add_option('--background', '-b', dest='background_picture',
             help="""Picture to use for the desktop background""")

options, arguments = p.parse_args()

if options.background_picture:
    picture_path = options.background_picture
else:
    picture_path = "/Library/Desktop Pictures/Beach.jpg"

# generate a fileURL
file_url = NSURL.fileURLWithPath_(picture_path)

# make image options dictionary
options = {
    NSWorkspaceDesktopImageScalingKey: NSImageScaleProportionallyUpOrDown,
    NSWorkspaceDesktopImageAllowClippingKey: True
}

# get shared workspace
ws = NSWorkspace.sharedWorkspace()

# iterate over all screens
for screen in NSScreen.screens():
    # tell the workspace to set the desktop picture
    error = ws.setDesktopImageURL_forScreen_options_error_(
        file_url, screen, options, None)