Writing Python bindings of existing C libraries – (3) – Building and Installing with distutils

HowTo, Igalia, Linux, Maemo (EN), Programmazione, Python 1 Comment »

In the last post of this series, we saw how to write a simple binding and we finished to build and install it manually. This is of course not a good way to manage the building/installation procedure.

In Python we can use a library called distutils that let us to automatize the building and installing process. I'll use the foo source code to create the package, so it will be easier to understand.

Using distutils

All we have to do is to write a setup.py file similar to this one:

from distutils.core import setup, Extension

foomodule = Extension('foo', sources = ['foo.c'])

setup (name = 'Foo',
       version = '1.0',
       description = 'This is a package for Foo',
       ext_modules = [foomodule])

As you can see, we have to first import needed modules with: from distutils.core import setup, Extension
then we create an entry for each module we have (in this case just one, "foomodule"). We then call the setup() method passing it all the parameters and our setup.py is complete.

Building and installing

To test it we can try to build the package in this way:

python2.5 setup.py build

if we want to install the module in our system:

python2.5 setup.py install

References

Making Maemo email client usable with GMail

HowTo, Igalia, Linux, Maemo (EN) 6 Comments »

I must admit, I wasn't using Maemo email client, because I did find it was simply unusable, at least with my GMail account.

I tried both POP3 and IMAP, but having about 25.000+ messages in my account, downloading just the headers was a job that the client simply couldn't manage.

Yesterday I knew about "recent mode" support in POP3, a functionality that GMail supports too. This mode allow you to download only last 30 days messages (in my case, no more than 1000)  so the client can manage them without any problem.

All you have to do to enable this mode is put the "recent:" string before the username. For example: if your username is "username@gmail.com" you have to write "recent:username@gmail.com". Important: this mode only works with POP3, not with IMAP.

To conclude, let me say thank you to the kind guy who let me discover this mode. Thank you Sergio! Now there is another thing I can do with my tablet!

Writing Python bindings of existing C libraries – (2) – A simple example of binding

HowTo, Igalia, Linux, Maemo (EN), Programmazione, Python 1 Comment »

Introduction

As I promised in the preceding post, I'll provide a very easy example of a python binding. Let's suppose we don't want to use the methods included in Python to sum two integer values and we want to do it in C and then call the add method from a python script. I'll write the complete source code first and then I'll explain all the parts of it.

Source Code

#include <Python.h>

static PyObject *foo_add(PyObject *self, PyObject *args)
{
	int a;
	int b;

	if (!PyArg_ParseTuple(args, "ii", &a, &b))
	{
		return NULL;
	}

	return Py_BuildValue("i", a + b);
}

static PyMethodDef foo_methods[] = {
	    { "add", (PyCFunction)foo_add, METH_VARARGS, NULL },
	    { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initfoo()
{
	    Py_InitModule3("foo", foo_methods, "My first extension module.");
}

How it works

First of all we have to include Python.h in our C file. This allows us to write an extension for Python language. To be able to include this header, we must have the python development packages installed in our system. For example in Debian based distributions we can install them with this command:

sudo apt-get install python2.5-dev

Every module has at least three parts. In the first part we write methods we want to call from the final python module: in this case we have a method called foo_add where "foo" is the name of the module and "add" the name of the method. Every method is declared as static PyObject. The method does anything particular except calling PyArg_ParseTuple to validate the input (we'll discuss this later), adding the two passed numbers and returning the result.

In the second part we have something like a dictionary, defined as static PyMethodDef and called foo_methods (where "foo" again is the name of the module). For each method we want to expose in our python module, we have to add something like this:

{"add", (PyCFunction)foo_add, METH_VARARGS, NULL}

where "add" is the name of the method we want to be visible in our module, (PyCFunction)foo_add is a pointer to our foo_add method, implemented in the C module, METH_VARARGS means that we want to pass some parameters to the function and the last one would be the description of the method (we can leave it NULL if we want).

Third part allows us to register the defined method/s and the module:

Py_InitModule3("foo", foo_methods, "My first extension module.");

Parsing Parameters

The PyArg_ParseTuple function extracts arguments from the PyObject passed as parameter to the current method and follows almost the sscanf syntax to parse parameters (in this case we had "ii" for two integers). You can fin the complete reference here: http://docs.python.org/c-api/arg.html

Building and installing

To build the module, we have to be in the source directory and execute this command:

gcc -shared -I/usr/include/python2.5 foo.c -o foo.so

then we've to copy the generated module to the python's modules directory:

cp foo.so /usr/lib/python2.5/site-packages/

Testing our module

Testing the module is really easy. We've to start a python shell or create a python script with the following source code:

import foo
print foo.add(2, 3)

if all is working fine, the printed result should be 5

References

python2.5-dev
python2.5-dev

Writing Python bindings of existing C libraries – (1) – Introduction

HowTo, Igalia, Linux, Maemo (EN), Programmazione, Python 2 Comments »

This summer I'm having the pleasure of working in Igalia (a spanish free software company) for a couple of months and they assigned me to an interesting project: developing Python bindings for MAFW library (a Maemo multimedia library that will be used in Fremantle release).

Having the opportunity to work both with C (yes, Python bindings are almost C code) and Python (it's a good practice to write unittest of all implemented methods) it's a good way to improve my knowledges in both languages and since I wasn't able to find much documentation about these kind of things, I'm going to share my own experiences.

What is a Binding?

A binding is a Python module, written in C language, that allows Python developers to call functions from existing C libraries from their python applications. It's just like a "bridge" from C world to Python one.

Why writing bindings?

There are a couple of reasons to write python bindings instead of writing a library in python language from scratch.

First of all I don't think is good duplicating code, so if a library already exists and it's written in C, why writing it again in another language? There's no reason. A lot of code already exist in C world and all we have to do is to create a bridge with python world.

Another good reason, in particular when a C library doesn't exist yet, is the fact that python code is slower than C code for some tasks (for example multimedia codecs). In these cases is good to implement the core library in C language and then create a python binding for it.

Coming next

As the title of this post says, this is only an introduction to the subjects I'm going to write about. If you have any particular request about any argument you would like to read, please feel free to leave me a comment. Next posts will talk about these things:

  • A simple example of binding: I'll write a simple library in C language and I'll show how to create the relative python binding, providing complete source code and an example for python developers.
  • Building and installing python bindings with distutils: I'll explain how to use distutils to build and install the binding (using the well know method "python setup.py install").
  • Defining new types: this post will be about how to write new types in C language and being able to use them from python code.
  • Using codegen to write bindings: I'll explain how to use codegen utils to automate lot of tasks, to generate the most part of binding code and how to customize the generated code using overrides.

Ridimensionare immagini automaticamente con un batch e ImageMagick

HowTo, Linux No Comments »

Spesso capita di dover compiere azioni noiose e ripetitive su delle immagini, come ad esempio ridimensionarle o salvarle in formati diversi da quello originale. Queste operazioni possono richiedere moltissimo tempo, soprattutto se abbiamo a che fare con una grande quantità di immagini.

Per chi usa Linux è disponibile però l'utility ImageMagick, che unita ad un pizzico di script in bash ci permette di risolvere agevolmente il problema.

Per prima cosa è necessario installare il tool sulla propria distribuzione. Su Ubuntu (o in qualsiasi altra distribuzione basata su Debian) procedere nella seguente maniera:

sudo apt-get install imagemagick

A questo punto basta posizionarsi nella cartella dove si trovano le immagini (vi consiglio di crearvi una copia a parte delle immagini da modificare, visto che lo script andra' a lavorare direttamente su quelle originali) ed eseguire un comando come questo:

find ./ -iname '*.JPG' -exec convert '{}' -resize '1024' '{}' \;

Questo comando convertirà tutte le immagini .JPG che trova in un formato di 1024 pixel di larghezza, mantenendo ovviamente le proporzioni dell'immagine originale.

Risolvere il crash all’avvio di Songbird su Ubuntu

HowTo, Linux, Ubuntu 3 Comments »

songbird_screenshot_0Se si prova a far girare la versione di Songbird scaricabile dal sito ufficiale su Ubuntu (ma il problema sembra riguardare anche altre distribuzioni visto che si tratta di un bug del driver Nvidia) si otterrà quasi sicuramente un crash dell'applicazione stessa.

Per risolvere il problema è sufficiente disinstallare un plugin (libvisual-0.4-plugins) utilizzando il seguente comando: sudo apt-get remove libvisual-0.4-plugins

Una nota negativa: questo bug è presente fin dalla versione 8.10 di Ubuntu... che aspettano a correggerlo invece di far ricorrere gli utenti a questi trucchetti?

Come passare dalla modalità enduser alla modalità developer su Fonera 2

HowTo, Linux, Recensione No Comments »

Fino ad ora, i possessori di Fonera 2.0 che volevano passare alla modalità "developer" (e quindi avere anche l'accesso via SSH) dovevano flashare la fonera con un'apposita immagine, facendo uso del cavo seriale oppure della procedura con il cavo di rete che utilizza Redboot.

Da oggi è disponibile un nuovo plugin che permette di passare automaticamente alla modalità developer, basta andare (ad esempio) su questa pagina del router: http://192.168.0.105/luci/fon_devices/fon_plugins

La Fonera passerà a questo punto in modalità developer e dovremo effettuare due reboot affinchè SSH sia attivato. Non dimenticatevi ovviamente di aprire l'accesso SSH nella configurazione del firewall della Fonera. Accedendo via SSH, vi troverete davanti questi messaggi:

andy80@andy80-jaunty:~$ ssh root@192.168.0.105
The authenticity of host '192.168.0.105 (192.168.0.105)' can't be established.
RSA key fingerprint is e5:6e:fc:70:73:44:f6:cd:30:bd:ac:2d:53:d2:ab:a9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.0.105' (RSA) to the list of known hosts.
root@192.168.0.105's password: 

BusyBox v1.11.1 (2009-04-17 12:45:57 CEST) built-in shell (ash)
Enter 'help' for a list of built-in commands.

                                        __
                                    _.-~  )
                         _..--~~~~,'   ,-/     _
                      .-'. . . .'   ,-','    ,' )
                    ,'. . . _   ,--~,-'__..-'  ,'
                  ,'. . .  (@)' ---~~~~      ,'
                 /. . . . '~~             ,-'
                /. . . . .             ,-'
               ; . . . .  - .        ,'
              : . . . .       _     /
             . . . . .          `-.:
            . . . ./  - .          )
           .  . . |  _____..---.._/ ____ Seal _
     ~---~~~~----~~~~             ~~                

                      Flipper                       

--------  Fonera 2.0 Firmware (v2.2.5.0) -----------
      * Based on OpenWrt - http://openwrt.org
      * Powered by FON - http://www.fon.com
----------------------------------------------------
root@Fonera:~# uname -a
Linux Fonera 2.6.26.2 #9 Tue Apr 21 11:32:31 CEST 2009 mips unknown
root@Fonera:~#

Cercherò prossimamente, nel caso ci sia interesse, di scrivere qualche post piu' approfondito su questa nuova Fonera, in modo da mostrare le caratteristiche di questo dispositivo.

Ubuntu 9.04 (Jaunty) su Asus EeePC 901

EeePC, HowTo, Linux, Recensione, Ubuntu 12 Comments »

eee-pc-901Con l'uscita della versione 9.04 di Ubuntu Linux, questa distribuzione ha veramente fatto passi da gigante per quanto riguarda il supporto ai netbook. Oltre a rilasciare una versione specificatamente pensata per i piccoli device (che integra di default l'interfaccia Notebook Remix), sono stati inclusi nel kernel tutti i moduli necessari a far funzionare le periferiche di questi device.

Per installare Ubuntu sull'EeePC dobbiamo per prima cosa procurarci la ISO dell'ultima versione e poi utilizzare una delle seguenti utility per preparare una chiavetta USB (da almeno 1 Gb) che ci permetterà di effettuare l'installazione: USB Startup Disk Creator, disponibile a partire dalle ultime versioni di Ubuntu (si trova in System-->Administration) oppure Unetbootin, che potete trovare a questo indirizzo: http://unetbootin.sourceforge.net/

Nel caso vogliate installare la versione NBR (Notebook Remix) di Ubuntu, che viene distribuita in formato .img dovete invece attenervi alle istruzioni che trovate su questa pagina: https://help.ubuntu.com/community/Installation/FromImgFiles

Una volta preparata la chiavetta USB (o in alternativa va bene anche una memoria di tipo SD) dovrete utilizzarla per fare il boot (vi ricordo che per fare il boot da USB dovete premere ESC nei primi secondi di accensione dell'EeePC) e procedere all'installazione come se fosse un normale PC. Se posso darvi un consiglio su come partizionare, vi suggerisco di utilizzare il disco da 4 Gb per la root / e quello da 16 Gb (o 12 Gb a seconda dei modelli) per la /home.

Completata l'installazione, al riavvio dell'EeePC avrete una piacevole sorpresa: tutte le periferiche saranno perfettamente riconosciute! Questo dimostra l'ottimo lavoro che è stato fatto per supportare questa fascia di dispositivi. E' necessaria tuttavia qualche altra piccola ottimizzazione per poter sfruttare al 100% il nostro netbook.

Per prima cosa vi consiglio di installare gli script di elmurato che vi permetteranno di utilizzare correttamente tutti i tasti funzione (Fn+Fx). Perchè possano funzionare dovrete anche installare sia un pacchetto presente nella Ubuntu, sia uno incluso nel tar.gz, seguendo le seguenti istruzioni:

sudo apt-get install dkms
sudo apt-get remove --purge nvidia-common
tar xzvf Jaunty_Eeeasy-Scripts.tar.gz
cd Jaunty_Eeeasy-Scripts
sudo dpkg --install asus-eee-dkms_3.0_all.deb
sudo ./eeeasy-scripts.sh

A questo punto non vi resta che riavviare il vostro EeePC e l'installazione sarà completata. Se vogliamo essere precisi, ci sono ancora un paio di piccole cose da migliorare. Noterete infatti che il tasto per abilitare/disabilitare il bluetooth non funziona correttamente. Si tratta di un bug del kernel 2.6.28 che viene fortunatamente risolto con la versione 2.6.29 di cui elmurato fornisce i pacchetti .deb già compilati: http://www.informatik.uni-bremen.de/~elmurato/EeePC/ (dovrete installare linux-headers-* e linux-image-* ).

La versione 2.6.29 del kernel include anche una versione aggiornata del modulo che fa funzionare la scheda wireless, permettendoci di avere un segnale piu' stabile.

Consiglio infine di aggiungere la seguente stringa in fondo al file /etc/modprobe.d/options (createlo se non esistesse): options psmouse proto=imps
questa opzione fa in modo che il touchpad funzioni meglio rispetto a come viene configurato di default.

Dropbox: 2Gb di disco online che si integrano con Windows, OSX e Linux

HowTo, Linux, Recensione, Windows 4 Comments »

dropbox_logoDa tempo stavo cercando un servizio che mi offrisse un piccolo spazio online, sempre accessibile ed utilizzabile come una chiavetta USB, per poterci mettere i miei dati ed averli sempre disponibili ovunque andassi. In questi giorni, dopo aver sentito parlare molto bene di Dropbox da parte di un amico, mi sono deciso a provarlo.

Dropbox offre 2 Gb (espandibili fino a 5 Gb invitando altre persone ad usare il servizio) di spazio gratuito, da utilizzare come disco personale. La cosa interessante è che non si tratta di una semplice cartella tipo FTP, ma tramite il loro client si integra perfettamente nel sistema operativo che stiamo utilizzando (Windows, OSX o Linux) e si occupa automaticamente di sincronizzare online le modifiche che facciamo ai file locali. I nostri file infatti si trovano sia sul nostro disco locale, sia in copia sul nostro spazio online.

Se ad esempio abbiamo installato il client sul nostro PC fisso e lavoriamo a dei file, questi vengono automaticamente sincronizzati online. Immaginiamo adesso di installare il client anche sul nostro portatile, non appena accediamo ad Internet i file verranno automaticamente sincronizzati, quasi in tempo reale.

Tra le altre funzionalità che il servizio offre, c'è anche quella di poter creare in automatico delle gallerie fotografiche. E' sufficiente creare una sotto cartella dentro la cartella Photos predefinita ed in automatico verrà creata la fotogallery.

Per quanto riguarda la sicurezza dei nostri file, quello che mettiamo su Dropbox rimane accessibile solo a noi, fatta eccezione per quello che viene messo nella sotto cartella Public. Il trasferimento dei file dal nostro PC allo spazio online inoltre avviene in modo cifrato. Nessuno però ci garantisce che i nostri documenti, uan volta sui server di Dropbox, non vengano sbirciati da qualcuno... il mio consiglio quindi è quello di crearsi una ulteriore sotto cartella, magari chiamandola Secure, e metterci dentro un file di Truecrypt sul quale andremo a montare la nostra cartella cifrata. In questo modo il file di Truecrypt sara' sincronizzato online, ma il suo contenuto sara' inaccessibile a chiunque, eccetto noi.

Un'ulteriore doverosa precisazione: il client che installiamo sul nostro PC non è opensource. A parte questo piccolo difetto, il servizio è veramente valido! Per chi avesse bisogno di maggiore spazio, esiste anche una versione a pagamento del servizio, dove per 10$/mese vengono messi a disposizione 50 Gb di spazio.

Chi volesse provare il servizio, puo' iscriversi utilizzando questo link: https://www.getdropbox.com/referrals/NTgzNTM0MTk

In questo modo sia voi che io guadagneremo +250 Mb di spazio da aggiungersi ai 2 Gb che vengono dati di base.

Develop a GPS-aware application for the Nokia N810

HowTo, Linux, Maemo (EN), Programmazione, Python 2 Comments »

Paul Ferrill has written a serie of three articles about writing a GPS-aware application for the Nokia N810, using the Maemo SDK, Eclipse and PluThon plugin.

Here is the complete serie:

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in