Skip to content

Instantly share code, notes, and snippets.

@onecooltaco
Forked from calum-github/change_desktop.py
Last active August 29, 2015 14:24
Show Gist options
  • Save onecooltaco/fd88af97af7656d5f80c to your computer and use it in GitHub Desktop.
Save onecooltaco/fd88af97af7656d5f80c 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.
Tested on Mountain Lion and Mavericks. Forked from https://gist.github.com/hunty1/548edaf7e913c8f4e06b,
which was inspired by Greg Neagle's work: https://gist.github.com/gregneagle/6957826
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
'''
from AppKit import NSWorkspace, NSScreen
from Foundation import NSURL
import argparse
import sys
parser = argparse.ArgumentParser(description='Sets the desktop picture on all screens. \
If more than one image path is provided, will match the file by parameter position \
to screen index in the NSScreen.screens array. Otherwise uses first parameter for all screens.')
parser.add_argument('file',
nargs='+',
help='The file path to the images. At least one is required.')
args = vars(parser.parse_args())
if args['file']:
picture_paths = filter(None, args['file'])
else:
print >> sys.stderr, 'You must supply a path for the desktop picture'
exit(-1)
# make image options dictionary
# we just make an empty one because the defaults are fine
options = {}
# get shared workspace
ws = NSWorkspace.sharedWorkspace()
screens = NSScreen.screens()
for index, screen in enumerate(screens):
try:
picture_path = picture_paths[index]
except IndexError:
picture_path = picture_paths[0]
file_url = NSURL.fileURLWithPath_(picture_path)
# tell the workspace to set the desktop picture
(result, error) = ws.setDesktopImageURL_forScreen_options_error_(
file_url, screen, options, None)
if error:
print error
exit(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment