Skip to content

Instantly share code, notes, and snippets.

@cbron
Forked from cbronazc/gist:5767996
Last active December 18, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbron/5806963 to your computer and use it in GitHub Desktop.
Save cbron/5806963 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import json
import urllib2
running = True
hdr = { 'User-Agent' : 'Someone is browsing reddit on their console' }
print "`exit` exits"
while running:
sub = str(raw_input("Enter a subreddit: "))
if sub == "exit":
running = False
continue
# Make the call
try:
req = urllib2.Request('http://reddit.com/r/'+ sub + '.json', headers=hdr)
response = urllib2.urlopen(req)
data = json.loads(response.read())
except urllib2.HTTPError, err:
print "Fetch failed"
continue
# print headers
headers = ('Num', 'Up', 'Down', 'Title')
for h in headers:
print "%-6s" % h,
print "\r"
print ("-"*6 + " ")*len(headers)
# loop first 10 json stories and print
for index, s in enumerate(data['data']['children'][0:10]):
line = s['data']
columns = (index + 1, line['ups'], line['downs'], line['title'])
for c in columns:
print "%-6s" % c,
print "\r"
print "\n"
else:
print "Goodbye"
# In Bash
#
# mv reddit.py reddit
# chmod +x reddit
# cd /usr/local/bin/
# sudo ln -s ~/test/reddit .
#
# Now you can just type 'reddit' in the console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment