Skip to content

Instantly share code, notes, and snippets.

@tmelz
Last active January 1, 2016 12:18
Show Gist options
  • Save tmelz/8143338 to your computer and use it in GitHub Desktop.
Save tmelz/8143338 to your computer and use it in GitHub Desktop.
Script to update wallpaper with picture from Subreddit on a Mac
#!/usr/bin/env python
# encoding: utf-8
# Fun script to download reddit pics and set as wallpaper.
# Easiest way to do this is to point to a directory
# then have Mac set to load random picture from directory
# (say every hour).
# Then set a cron job to run this script every hour
# and a job to delete old pictures every few days
# Ex:
#
# ~/bin $ cat remove_old_wallpapers.sh
# find /Users/timm/Pictures/Wallpapers/ -mtime +2 -type f -delete
# # timm's crontab
#
# # update wallpaper
# @hourly /usr/local/bin/python /Users/timm/bin/reddit_wallpaper.py &> /dev/null
# @daily /bin/sh /Users/timm/bin/remove_old_wallpapers.sh &> /dev/null
import subprocess
import random
import praw
import requests
PICTURE_FILETYPES = ['jpg', 'png']
# PIC_DIR = "/Users/timm/Pictures/Wallpapers/"
PIC_DIR = "/Users/timm/Desktop/"
PIC_FILEPATH = PIC_DIR + "{0}.{1}"
# What subreddits to search
# SUBREDDITS = ['spaceporn', 'earthporn', 'botanicalporn',
# 'waterporn', 'skyporn', 'fireporn', 'cityporn']
SUBREDDITS = ['earthporn']
# How many submissions to look at (picture is chosen randomly from pool
IMG_LIMIT = 100
def get_img_submission(subreddit):
reddit = praw.Reddit(user_agent="Wallpaper script")
subs = list(reddit.get_subreddit(subreddit).get_hot(limit=IMG_LIMIT))
img_subs = [sub for sub in subs if any(sub.url.endswith(ext) for ext in PICTURE_FILETYPES)]
return random.choice(img_subs)
def get_ext(url):
return url.split(".")[-1]
def sanitize_filename(raw):
return "".join(x for x in raw if x.isalnum())
def download_picture(sub):
file_path = PIC_FILEPATH.format(sanitize_filename(str(sub.title)), get_ext(sub.url))
args = ["/usr/local/bin/wget", "-O", file_path, sub.url]
print ' '.join(args)
p = subprocess.Popen(' '.join(args), shell=True)
stdout, stderr = p.communicate()
return file_path
def main():
sub = get_img_submission('+'.join(SUBREDDITS))
filename = download_picture(sub)
if __name__ == '__main__':
main()
@phillystafford
Copy link

Hi! I stumbled across this script and I think it is a brilliant idea but could you please provide instructions on how to run the script? When I try to run it in terminal on the Mac I get the following error:

$ python3 reddit_wallpaper.py
File "reddit_wallpaper.py", line 56
print get_name(url), get_ext(url)
^
SyntaxError: invalid syntax

@tmelz
Copy link
Author

tmelz commented Oct 2, 2014

@woppers try with python2.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment