Archivos para Julio, 2009

Interfase pythonera a Commandlinefu

Buenas gente!

Hace rato que no escribía :( . Bueno, ahora tengo algo bueno por lo menos para postear, ja ja. Estuve trabajando en una interfase para el espectacular sitio Commandlinefu que a tantos linuxeros/unixeros ha ayudado.

Basado en la API publicada por el sitio, hice este script, que por el momento está en su versión 0.01, pero por lo menos anda. Posiblemente luego le agregue más funciones. Por lo pronto, me falta documentar todo, y darle una función real a los manejadores de json y rss.

Espero que les sirva! Las sugerencias serán bien recibidas.

Saludos a todos.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http ://www.gnu.org/licenses/>.

import re
import sys
import urllib
import getopt
import pprint

available_libraries = { 'json':False,
                        'feedparser':False,
                    }

try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        pass
    else:
        available_libraries['json'] = True
else:
    available_libraries['json'] = True

try:
    import feedparser
except ImportError:
    pass
else:
    available_libraries['feedparser'] = True

import string
import binascii

interface_url = string.Template('http://www.commandlinefu.com/commands/${command}/${format}/')

formats = ['json', 'rss', 'plaintext']

browse_all_commands = 'browse/sort-by-votes'

def tagged_commands(a_command, sort_criteria=163):
    return 'tagged/%d/%s' %(sort_criteria, a_command)

def matching_commands(query):
    b64_query = binascii.b2a_base64(query).strip()
    return 'matching/%s/%s' %(query, b64_query)

short_opts = 'fjhst'
long_opts = 'feed json help search tag'.split()

def process_plaintext (data):
    """ Function doc """
    print data.read()

def process_json (data):
    """ Function doc """
    if not available_libraries['json']:
        return
    data_json = json.loads(data.read())
    pprint.pprint(data_json)

def process_rss (data):
    """ Function doc """
    if not available_libraries['feedparser']:
        return
    data_rss = feedparser.parse(data.read())
    pprint.pprint(data_rss)

def main (argv=sys.argv[1:]):

    prefered_format = 'plaintext'
    command_to_query = browse_all_commands

    try:
        opts, args = getopt.getopt(argv, short_opts, long_opts)
    except getopt.GetoptError, err:
        print "Uso:"
        return
    for op, arg in opts:
        if op in ('-f', '--feed'):
            if available_libraries['feedparser']:
                prefered_format = 'rss'
        elif op in ('-j', '--json'):
            if available_libraries['json']:
                prefered_format = 'json'
        elif op in ('-h', '--help'):
            print "help!"
        elif op in ('-s', '--search'):
            try:
                command_to_query = matching_commands(args[0])
            except Exception, e:
                pass
        elif op in ('-t', '--tag'):
            try:
                command_to_query = tagged_commands(args[0])
            except Exception, e:
                pass
        else:
            print "Not implemented, will not handle %s" %op

    process = { 'plaintext': process_plaintext,
                'json': process_json,
                'rss': process_rss,
            }

    url = interface_url.substitute(command=command_to_query, format=prefered_format)
    process[prefered_format](urllib.urlopen(url))

if __name__ == '__main__':
    main()

    sys.exit(0)   

Dejar un comentario