Skip to content

Instantly share code, notes, and snippets.

@MercuryRising
Created November 6, 2012 04:27
Show Gist options
  • Save MercuryRising/4022546 to your computer and use it in GitHub Desktop.
Save MercuryRising/4022546 to your computer and use it in GitHub Desktop.
Reddit Command Line
#! /usr/bin/env python2
# Requests is much easier to use than urllib
import requests
# needed for sys.exit()
import sys
# Wrap it in a function you can, you might find a use for it later
# We're adding subreddit functionality, but still providing a default
def print_top(subreddit='all'):
# Make it fancy! Let's let the user pick the subreddit
url = "http://www.reddit.com/r/"+subreddit+".json"
# This line
r = requests.get(url)
# replaces this
# all = urllib.urlopen(url).read()
# content = json.loads(all.decode("utf8"))
# Little bit easier to remember, r.get(URL) than that monstrosity
stories = {}
# We're going to get a little fancy and allow the user to enter the subreddit they'd like to see
# We want to see how many stories we're getting before, by calling len() on the data's children
print "\nTop %s stories for %s\n" %(len(r.json['data']['children']), subreddit)
# Use enumerate to keep track of your position in a loop.
# We could say content = r.json['data']['children'] if we wanted
# r.json is just what it sounds like, a dictionary of the json in the response
for index, x in enumerate(r.json["data"]["children"]):
# A couple helper variables to keep the sanity
data = x['data']
# Converting the index to a string allows greater flexibility when we want to interact
# Instead of trying to convert the entries into an int, we can just use strings
index = str(index)
# This was more of an cosmetic change, but it's a little easier to parse if the self
# indicator is closer to the data you care about (the position)
if data['selftext'] != "":
# Might as well be consistent and either use string concatenation or formatting.
# Switched to %s because we're using strings now.
# Call strip to prevent newlines from being added where they shouldn't
print "[%s][S] %s" % (index, data['title'].strip())
# Either join or concat, I like concat more (it's easier to see what's going on)
# When we call a self post, we'll see the title, and the body, with a little bit of
# newline formatting to make it easier to read (less like a wall of text)
story_data = "\nTitle: " + data['title'] + "\n\n" + data['selftext'] + "\n"
stories[index] = story_data
else:
# If it's not a self post, we just print it and forget it.
print "[%s] %s" %(index, data['title'].strip())
# add a newline after the subreddit list
print "\n"
# return stories so we can access the data outside the function
return stories
print "Amazing reddit loader"
print "enter 'exit' to quit"
print "enter /r/SUBREDDIT to load a specific subreddit"
print "enter blank to reload the last subreddit"
# Call our function to print the top of all
stories = print_top()
subreddit = "all"
while True:
st = raw_input("Which selfpost would you like to view? > ")
if st == "exit":
sys.exit()
# This is our fancy subreddit picker
# The usage is /r/SUBREDDIT and that will load the new subreddit
elif "/r/" in st:
subreddit = st.strip("/r/")
stories = print_top(subreddit)
elif st == "":
# This lets us reload the last picked subreddit
stories = print_top(subreddit)
else:
# A better way to get values from dictionaries if the value might not be there
# (better than a try except) is to use get
# get allows you to defined a default value if the key is not in the dictionary
# This is great for programs that aren't always going to give you back a well formed
# value, you can do this to give a good default value that makes your program not choke
print stories.get(st, "Sorry, that is not a self-post")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment