Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/python
'''
Script to set the OSX desktop background to the top picture from a given
subreddit.
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:
http://1klb.com/blog/desktop-background-on-os-x-109-mavericks.html/
'''
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'}:
continue
with codecs.open(os.path.join(dirname, 'meta'), 'w', encoding='utf-8') \
as outfile:
outfile.write(sub.title)
outfile.write('\n')
outfile.write(sub.url)
outfile.write('\n')
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):
shutil.rmtree(dirname)
os.mkdir(dirname)
img_file = download_top_link(subreddit, dirname)
print("setting background to {}\n".format(img_file), file=sys.stderr)
with codecs.open(os.path.join(dirname, 'meta'), 'r') as f:
print(f.read().strip(), file=sys.stderr)
set_wallpaper(img_file)
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()
main(**vars(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.