Archive for 2009

Python: using a module written in C

Tuesday, June 9th, 2009

This is a brief tutorial for using a module written in C inside a Python program. It’s a summarized recipe fr those who want to run and test something fast without falling in reading the docs, but I recommend to read.

[1] http://docs.python.org/extending/extending.html
[2] http://docs.python.org/extending/building.html

Let’s write a module called spam, the same as the example in [1], our spammodule.c will look like this:

#include 
static PyObject *SpamError;
static PyObject *
spam_system(PyObject *self, PyObject *args){
    const char *command;
    int sts;
    if (!PyArg_ParseTuple(args, “s”, &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue(”i”, sts);
}
static PyMethodDef SpamMethods[] = {
    {”system”,  spam_system, METH_VARARGS,
     “Execute a shell command.”},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};
PyMODINIT_FUNC
initspam(void){
    PyObject *m;
    m = Py_InitModule(”spam”, SpamMethods);
    if (m == NULL)
        return;
    SpamError = PyErr_NewException(”spam.error”, NULL, NULL);
    Py_INCREF(SpamError);
    PyModule_AddObject(m, “error”, SpamError);
}

Ok, now, rather than compiling it by hand, let’s use an automated mechanism: distutils [2]. Edit a setup.py file which will be the “driver” for compile and make yur module in C importable from Python.

from distutils.core import setup, Extension
module1 = Extension('spam', sources = ['spammodule.c'])
setup(name = ‘PackageName’, version = ‘1.0′, description = ‘This is a demo package’,
          ext_modules = [module1])

Compile the C module using the driver: $ python setup.py build
An example of the output I get:

running build
running build_ext
building 'spam' extension
creating build
creating build/temp.linux-x86_64-2.6
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c spammodule.c -o build/temp.linux-x86_64-2.6/spammodule.o
creating build/lib.linux-x86_64-2.6
gcc -pthread -shared build/temp.linux-x86_64-2.6/spammodule.o -L/usr/lib -lpython2.6 -o build/lib.linux-x86_64-2.6/spam.so

Test it!, depending on your platform and settings you’ll get a directory tree created, I’ll cd into mine:

$ cd build/lib.linux-x86_64-2.6
$ python
>>> import spam
>>> spam.system('echo "hello world"')
hello world
0
>>>

re-quemado

Monday, June 1st, 2009

Peñarol presentará hoy ante la AUF una propuesta para que la liguilla “la jueguen todos”: que los 6 primeros clasifiquen al campeonato uruguayo y los demás a las copas

Estaría todo pronto para que en las próximas horas la dirigencia de peñarol presente ante la AUF una propuesta innovadora para el fútbol profesional uruguayo, jugar primero la liguilla y que la misma clasifique al uruguayo y los que no lleguen, vayan a las copas. “Nos parece lógico, esto está muy quieto, hay que modificar el reglamento nuevamente, ya hace casi un año que está igual!”, declaró el presidente de peñarol el sr. Damianchi en diálogo con la prensa deportiva, “tenemos que ajustarnos, en todo el mundo se está ideando algo parecido. Así podemos optar por dedicarnos a una o a otra cosa, por ejemplo, ahora estaríamos en zona de Copa Libertadores. El año que viene entramos al uruguayo y así…”.  -Pero usted ha tenido apoyo del resto de la dirigencia del club?. -”Que si he tenido apoyo? pero por favor pibe” -Pero no cree que esto perjudica a algunos equipos? -”Peñarol es peñarol” En definitiva no se pudieron obtener argumentos sólidos en favor de la propuesta, lo cual indica que la misma tiene firmes chances de ser adoptada por la AUF.

Penca de la copa libertadores 2009

Friday, March 6th, 2009

Amigos, se largó la penca de la libertadores, en predgame.com

La idea es la de siempre, divertirnos entre amigos jugando un poco. Por que un dominio nuevo? bueno, la idea es que el sitio vaya creciendo, por ahora se está desarrollando de a poco, en los ratos libres :) pero la idea es seguirlo. Django y Pinax han ayudado mucho a la rápida puesta en producción del sitio pero lógicamente se necesitan ajustes. Tenemos muchas ideas desde hace tiempo para esto con varios amigos, el sitio esta listo para jugar pero le faltan muchas features muy necesarias que iran saliendo de a poco, por ejemplo:

  • Aviso de falta de pronosticos por email
  • Scraping de partidos y resultados usando scrapy
  • Autenticacion segura
  • Multipenca support
  • Mas idiomas en la i18n
  • Muchas mejoras en la gui
  • Conseguir sponsor para que hayan premios :)

saludos !!

Playing with python-rpy2

Thursday, February 26th, 2009

The goal was to prepare a little prototype to show the potential of R (r-cran) when used via its Python bridge python-rpy2, then show the results in a web application, for example, using django.

In this example (in spanish) we take a CSV database and use R to present some calculations.

Thanks to Martin Sanguinetti who have motivated me and told me the R basics to make this example.

An example plot using python-rpy2

[A classical example plot using python-rpy2]

Python2.6 with mod_python in debian

Thursday, January 15th, 2009

As you may know, there are no packages yet for Python2.6 in debian or ubuntu. If you want to install it you can do it by hand and it will work perfectly (it did for me)

Google a bit and you will find this post: http://blog.pythonaro.com/2008/10/horrible-hack-to-get-python-26-on.html

You can follow the steps in the post without problem, then remember to update your supported and default versions under /usr/share/pyhton/debian_defaults

Also you can link modules available in 2.5 to be used by 2.6, for example Ipython, it works perfectly. Do symlinks from python2.6/site_packages/ pointing python2.5/site_packages. Although this is not the correct way, the correct way should be reinstall those modules under your new configuration.

But what about mod_python? it still remains to Python2.5 right? YES

Well, you have to do the same, download it from modpython.org and make and make install, be sure to install apache2-dev it will provide you with a tool needed in the compilation time.

All should work, also django is working perfectly in my new Python & mod_python 2.6 conf. under debian.

cheers!

Windows evolution

Monday, January 12th, 2009

- Hola, vengo a comprar una laptop con lo del plan ceibal.

- Bien, tengo esta winky-plinky-dupper a buen precio.

- ¡Pero esto es un anti virus!

- Si, es que ya dejamos de vender con windows, ahora directamente vendemos el antivirus pronto, listo para usarse, mirá!: te viene la opción de cuarentena, de curar, de eliminar, –click, click– todo, todo.

Se actualiza solito por internet, bien familiar.

Ya no tenés que andar haciendo los pasos previos, tipo, navegar un par de semanas, usar el word, instalar jueguitos y todas esas cosas, ya directamente usás el antivirus que es el posta!, eh!?

- Ah tenés razón che!, los virus están salados, me dijeron que hasta te pueden reventar el disco duro.

- Pff! Si, si, pueden hacer cualquier cosa, viste como-eh!

- Bueno dale, llevo esa.

- Perfecto!