viernes, octubre 24, 2008

Descriptors y Decorators

Hay un post de Ian Bicling sobre como usarlos en combinación.
En dicho post hay unas referencias a un HowTo sobre Descriptors (interesante leer los comentarios) y a un nuevo tutorial sobre Decorators de Bruce Eckel.

Antes de comentar al respecto postear dos referencias mas sobre Bruce: una en la que habla sobre la que será su próxima publicación, Python 3 Patterns and Idioms; y otra que la que habla porque no habrá un Thinking in Python (es interesante además porque da unas referencias a otros libros).

Bueno volviendo al tema del post...
Realmente puedes leer sobre los descriptors, pero realmente para pillarlos hay que trastear con ello y leerlo con muchaaaa calma (y lo ideal sería probando los ejemplos). Pero bueno.... El tutorial sirve para pillar la idea.

El de los descriptors por el contrario si que es sencillo. Y son muy muy potentes.
Una de las cosas que eché de menos cuando empecé con python es el poder tracear las entradas y salidas de funciones o métodos. Esto típicamente se hace en C/C++ con macros.
Pues bien... con descriptors es posible hacerlo.

El pero es que con los descriptors en principio pareceque que tienes que modificar el código fuente. Pero no!!! Aunque es la forma evidende de usar los descriptors no es la única, ya que todo el mecanismo es dinámico. De hecho... esto se podría hacer sin los descriptors, ya que todo en python es dinámico...
Que quedo con la copla para experimentar con ello en un futuro...

miércoles, octubre 22, 2008

Usando webkit desde python

Antes de nada comentar que no lo he probado, pero me gustaría...
Se puede usar webkit desde python a bravés de pywebkitgtk.

Relacionadas, parte de pywebkitgtk, veo que también existen Pyjamas and python-qt4-webkit.

Intentando investigar un poquito sobre este tema... que he encontrado este post de comp.lang.pyhon (enfocado principalmente a ejecutar javascript, pero relacionado):

"pyv8 is the newest addition: http://advogato.org/article/985.html

it's a python wrapper around google's v8 javascript execution
library.

then there's pykhtml: http://paul.giannaros.org/pykhtml/

it's a python wrapper around KHTML, providing very convenient access
to KDE's HTML capabilities: what pykhtml does is "pretends" that the
GUI part of KDE doesn't exist, so you can run your program as a
command-line shell; it will execute the javascript, which you will
have to wait a bit for of course; then you can walk the DOM tree
(using pykhtml bindings) using pykhtml.DOM.getElementById() and
getElementsByTagName("a") etc. etc. looking for the URLs.

there's even an AJAX example included which does 1-second polling of
the DOM model, waiting for a spell-checking web site to deliver the
answer.

then there's webkit, with the new glib bindings:
https://bugs.webkit.org/show_bug.cgi?id=16401

which are then followed up by python bindings to _those_ bindings:
http://code.google.com/p/pywebkitgtk/issues/detail?id=13

this will also allow you to execute arbitrary javascript - again, it's
similar to KHTML and in fact webkit really _is_ the KDE KHTML code
(JavaScriptCore, KJS etc) but forked, improved, etc. etc.

unfortunately, the glib bindings are tied - at three key and strategic
locations - to gtk at the moment, which will take _very_ little work
to "un"tie them [pay me and i'll do the work], so you would need to
create a blank gtk window - just like is done with pykhtml, behind the
scenes.

it would be a very simple task to create a "dummy" - console-based -
port of webkit, providing an array of callbacks which you must hand to
the library. at the moment, the design of webkit is not particularly
good in this respect: there are three ports, gtk, wx and qt, which are
heavily tied in to webkit. it would be a _far_ better design to be
passing in a struct containing function callbacks (rather a lot of
them - about eighty!) and then what you could do is have a "console"-
based port of webkit, which would do the job you needed.

alternatively, if you don't mind wrapping a binary application with
e.g. Popen3 then look at the webkit DumpRenderTree application, paying
particular attention to using the --html option. you won't have any
control over how long the javascript is executed for. after an
arbitrary and small period of time, DumpRenderTree _stops_ executing
the javascript and prints out the HTML DOM model (in a non-html-layout
fashion - it's used for debugging and testing purposes but will
suffice for your purposes).

so, as it stands, pywebkitgtk is _no worse_ than pykhtml, but with a
little bit of tweaking, the "gtk" could be removed from "pywebkitgtk"
and you'd end up with... ohh... call it "pywebkitglib" ... which would
be much better as a stand-alone library, for your purposes

then there's also "spidermonkey", which is mozilla's javascript
engine. i haven't investigated this option: haven't had a need to.

then there's also PyXPCOMExt, which is embedding python into mozilla,
and from there you have PyDOM, which allows you access to the DOM
model of the mozilla "thing". so, if you don't mind embedding your
application into XULRunner, you've got a home for executing your app
and obtaining the urls, post-javascript-execution.

the neat thing about PyXPCOMExt is that you have complete and full
access to python - so your app can make external TCP and UDP sockets,
you can embed an entire _server_ in the damn thing if you want (you
could embed... python-twisted if you wanted!) you can access the
filesystem - anything. absolutely anything. reason: the _entire_
python suite is embedded into the browser. every single bit of it.

that's about all i've been able to find, so far. there might be more
options out there. not that there aren't enough already :)

all of them will allow you complete and full access to execution of
javascript, including AJAX execution. which is why you'll need to do
that "polling" trick in many instances. "

lunes, octubre 20, 2008

Pasar de pdf a texto/html

Para extraer el texto del pdf, se de dos aplicaciones que funcionan bien:
Por lo visto en una etapa del pipeline de fast (de las que vienen disponibles), se usa xpf (no lo puedo asegurar al 100%).
Nosotros en cierta ocasión usabamos el segundo (¿o fue pdf2html?). Porque nos daba mejores resultados.

Si quieres hilar mas fino, y no depender de una aplicación externa existe Poppler.
Parece que ha habido un amago de hacer bindings a python para poppler...
Uno de los peor de poppler es que no hay documentación.

Dentro del paquete poppler-utils, hay utilidades de conversión.
He visto que existe el paquete pyPdf.

viernes, octubre 17, 2008

Primer curso python impartido


Bueno... ayer se acabó el primer curso python.

No se como habrá resultado, ya que es dificil verse desde fuera (estaría genial poderse ver grabado, para corregir posibles defectos). Pero creo que en general ha estado bien.
Aparte de mi exposición, el material desde luego si que creo que está bastante bien.
Tras la experiencia del curso, quizás podría retocar alguna cosa (muy poca), o por mi parte mirar con mas detalle alguna referencia. Pero la verdad... para un curso de 12 horas, poco mas puedo ampliar. El tiempo está muy bien ajustado ya.

Lo malo, pero esto ya es típico de los cursos dentro de una empresa, quizas un poco de falta de interés por algun alumno (bueno es la percepción desde el lado del profesor). Pero vamos.... esto es algo de esperar. Pero con que haya ya sólo uno con interés es suficiente. Aún así, la gente con menos interés ha podido ver de que va esto de python...

El peor día fue el primero, en el que empecé con un poco de tensión, pero una vez superada el resto bien.
El último día me lleve un chasco. Hice una demo sobre como con joins() la concatenación de cadenas es mas eficaz que usando el operador '+'. Y no fue así. Los tiempos salieron similares.... [1]

A la presentación que tenía preparada le añadí contenido de la presentación de Gustavo Picón, para hacerla mas amena. Sobre todo para el comienzo.

El hacer un curso en python, es realmente muy sencillo, por la interactividad que te permite el interprete.
A la hora de escoger ejercicios para realizar por el alumno, hay dos opciones: hacer muchos ejercicios sencillos, o hacer menos pero mas complejos (no por la dicitultad del problema, sino por que consitas en hacer aplicaciones que realmente hagan algo).
Me decidí por la segunda opción.
En cuanto a la teoría indicar, que la aproximación al contenido ha sido la de pensar, según mi experiencia que debería tener. Y a partir de ahí elaborarlo, tirando de distintas fuentes y metiendo muchas referencias externas.
Lo mas sencillo hubiera sido fusilar algo ya existente, pero no me interesaba esta aproximación (mucho mas cómoda para mi). Ahora cualquiera con interés puede ver libros, u otras presentaciones y el contenido será diferente.

Al final el curso está dividido en 4 partes correspondientes a 4 dias (3 horas por dia):
  • Teoría, jugar un poco con python
  • Ejercicio 1 y explicación
  • Teoría, comienzo de Ejercicio 2
  • Explicación ejercicio 2, y practica libre
Durante la realización de los ejercicios, he mostrado mas cosillas...

Ya para acabar, indicar que en la web hay muchas presentaciones (incluso videos). Ahí va un listado de presentaciones de guido.
Y el enlace a la presentación del curso: El mundo de python.

Notas:
[1] Efectivamente, hay novedades que no sabia sobre esto. Por lo visto desde CPython 2.4 según What's New in Python 2.4: "String concatenations in statements of the form s = s + "abc" and s += "abc" are now performed more efficiently in certain circumstances. This optimization won't be present in other Python implementations such as Jython, so you shouldn't rely on it; using the join() method of strings is still recommended when you want to efficiently glue a large number of strings together."

jueves, octubre 16, 2008

NTLM Authorization Proxy Server

Relacionado con el firefox, ya comenté hace tiempo de una extensión interesante. MM3-ProxySwitch. Es interesante si necesitamos cambiar frecuentemente de proxies.

Otra utilidad muy util es un script en python que te permite autentificarte ante un proxy NTLM.
Si tenemos el MS Proxy Server y no estamos en el dominio, con firefox será un infierno navegar, ya que nos pedirá que nos autentifiquemos con cada petición. Este script, NTLM Authorization Proxy Server, lo soluciona.
Su autor Dmitry Rozmanov.

He indagado en Pypi, pero no está. Eso si, me he encontrado otro proxy disponible.