Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script to set the OSX desktop background to the top picture from a given
NOTE: sets it for the current space (on all monitors), but not other spaces.
There doesn't seem to be an AppKit API to change it for all spaces.
TODO: set it in the sqlite db instead:
from __future__ import print_function, unicode_literals
import codecs
import os
import re
import shutil
import subprocess
import sys
import AppKit
import Foundation
import praw
import requests
# TODO: multireddits
def download_top_link(subreddit, dirname):
r = praw.Reddit(user_agent='my_cool_background_changer')
subs = r.get_subreddit(subreddit).get_hot(limit=10)
for sub in subs:
ext = sub.url.rsplit('.', 1)[-1][-6:]
if ext.lower() not in {'jpg', 'jpeg', 'png'}:
with, 'meta'), 'w', encoding='utf-8') \
as outfile:
resp = requests.get(sub.url, stream=True, verify=False)
img_fname = os.path.join(dirname, 'background.' + ext)
with open(img_fname, 'wb') as outfile:
shutil.copyfileobj(resp.raw, outfile)
return img_fname
raise TypeError("no images found")
def set_wallpaper(filename):
file_url = Foundation.NSURL.fileURLWithPath_(filename)
options = {
AppKit.NSWorkspaceDesktopImageScalingKey: AppKit.NSImageScaleProportionallyUpOrDown,
AppKit.NSWorkspaceDesktopImageAllowClippingKey: AppKit.NO,
AppKit.NSWorkspaceDesktopImageFillColorKey: AppKit.NSColor.blackColor()
ws = AppKit.NSWorkspace.sharedWorkspace()
for screen in AppKit.NSScreen.screens():
result, error = ws.setDesktopImageURL_forScreen_options_error_(
file_url, screen, options, None)
if result is not True or error is not None:
print(result, error)
subprocess.check_call(['killall', 'Dock'])
def main(subreddit='EarthPorn', dirname=os.path.expanduser("~/.background")):
if os.path.exists(dirname):
img_file = download_top_link(subreddit, dirname)
print("setting background to {}\n".format(img_file), file=sys.stderr)
with, 'meta'), 'r') as f:
print(, file=sys.stderr)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dirname', '-d', default=os.path.expanduser('~/.background'))
parser.add_argument('subreddit', default='EarthPorn', nargs='?')
args = parser.parse_args()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.