Created
June 2, 2012 14:38
-
-
Save livibetter/2858669 to your computer and use it in GitHub Desktop.
Random eats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Copyright 2012 Yu-Jie Lin | |
# MIT License | |
# | |
# Requires: | |
# https://bitbucket.org/activestate/python-recipes/overview | |
from random import random | |
import argparse | |
import sys | |
HAS_PYGMENTS = True | |
try: | |
from pygments import highlight | |
from pygments.lexers import get_lexer_by_name | |
from pygments.formatters import Terminal256Formatter | |
from pygments.styles import get_all_styles | |
except ImportError: | |
HAS_PYGMENTS = False | |
from recipeslib.recipesapi import RawRecipesAPI | |
def main(): | |
parser = argparse.ArgumentParser(description='Random eats.') | |
parser.add_argument('-l', '--lang', | |
default='python', | |
help='show recipe in the language (default: %(default)s)', | |
dest='lang') | |
parser.add_argument('-t', '--tags', | |
nargs='*', | |
help='show recipe with tags', | |
metavar='TAG', | |
dest='tags') | |
if HAS_PYGMENTS: | |
parser.add_argument('-s', '--style', | |
default='default', | |
help='highlighting style, "list" to get a list of styles (default: %(default)s)', | |
dest='style') | |
args = parser.parse_args() | |
if HAS_PYGMENTS and args.style == 'list': | |
print 'Available styles:' | |
for style in get_all_styles(): | |
print ' %s' % style | |
return | |
rapi = RawRecipesAPI() | |
# get total | |
results = rapi.query(tags=args.tags, lang=args.lang, per_page=1) | |
total_recipes = results['total'] | |
if not total_recipes: | |
print >> sys.stderr, 'No recipes to randomly eat!' | |
sys.exit(1) | |
# get recipe id | |
n = int(random() * total_recipes) + 1 | |
data = rapi.query(tags=args.tags, lang=args.lang, page=n, per_page=1) | |
recipe = data['data'][0] | |
# get recipe | |
recipe = rapi.recipe(recipe['id']) | |
recipe['link'] = 'http://code.activestate.com/recipes/%d/' % recipe['id'] | |
print_keys = ['title', 'author', 'tags', 'license', 'updated_date', 'link', | |
'lang', 'code'] | |
max_key_len = max(len(key) for key in print_keys) | |
for key in print_keys: | |
if key == 'code': | |
value = '' | |
else: | |
value = recipe[key] | |
print ('%%-%ds: %%s' % max_key_len) % (key, value) | |
code = recipe['code'] | |
if HAS_PYGMENTS: | |
lexer = get_lexer_by_name(recipe['lang'], stripall=True) | |
formatter = Terminal256Formatter(style=args.style) | |
code = highlight(code, lexer, formatter) | |
print code | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment