Posts Tagged ‘python’

ImportError: No module named interface

Thursday, March 18th, 2010

OS=Ubuntu 9.10
Python version=2.6
After install a zope module using pip, for example z3c.password your zope installation gets broken.

This is because pip have installed the module in /usr/local/lib/python2.6/dist-packages/zope and the original module zope.interface is in /usr/share/pyshared/zope/interface/ and has minor relevance when importing.

Quick fix:
cd /usr/local/lib/python2.6/dist-packages/zope
sudo ln -s /usr/share/pyshared/zope/interface/

Consumo de ADSL por mail - ANTELDATA

Monday, August 17th, 2009

cuentagigas.info es una interfaz simple para un bot(programa) que hace tiempo quería hacer para estar al tanto de cuántos gigas voy gastando en el adsl sin tener que estar entrando al sitio de anteldata, … si quieren probarlo:

cuentagigas.info

Detalles técnicos:

  • El robot actualmente revisa el consumo 2 veces por día y decide si hay que enviar o no una notificación a cada cuenta. Está hecho en Python, es un Scrapy-spider bastante simple. Si alguien quiere ver el código lo puedo publicar.
  • La interfaz es un Django-site también bastante simple.
  • Permite dar de alta varios emails, útil cuando varias personas usan el mismo adsl. También permite cancelar el envío de notificaciones o cambiar los datos asociados. Se irá mejorando en base al feedback recibido.
  • Funciona con usuarios de adsl y adsl móvil.

Gracias.

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
>>>

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. The code of the example is published here, you can browse it, download or even clone using mercurial.

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!

ReSTlides.com: Online ReST based presentations

Thursday, July 24th, 2008

When asked by a friend to present Python for the web for an university course, I though: “Why don’t present Python inside some Python-powered slides?” and for training purposes I’ve created http://restlides.com/ a django-powered site that allows us to create and share ReSructured Text based presentations, obviously it’s in an very early alpha version, created during a weekend, but it works and I’m afraid I’ll continue developing it, I have in mind many new features. That’s all, try it and of course, any feedback is welcome!

restlides.com

For deployment I’m using apache2 with mod_python and varnish an “state-of-the-art”[1] reverse proxy, very easy to install and configure, you only have to put apache to the back and connect varnish to it, then adjust varnish’s port to 80 in /etc/defaults.

[1] Althought it last release was in December’07, and no activity on its trac, quite dead, I wrote to Poul-Henning Kamp, its developer to get feedback about the situation.

… I asked: “Are there any people working?” … And he replied:

Yes, very much so, but we've not spent enough time on the wiki.
We hope to release version 2.0 in august.

Scrapy, an opensource screen scraping framework in Python

Monday, June 30th, 2008

Scrapy, an opensource screen scraping framework in Python

Look!, with this framework, you could easily crawl the web and take automatically that bit that you ever wanted! …  Better than this, you can take those similar bits from that bunch of cool websites you have bookmarked a long time ago and said “some day they will be useful”.  The day have arrived, you can take your hands on Python code and start programming your application to take all the stuff you want from the web. You will love standards more and more. Ahh!, and don’t forget to join us and help, the spirit of open source software is present once again, have fun scraper! http://scrapy.org/

Join strings recursively

Sunday, January 20th, 2008

I didn’t want to search for it, so I made mine:

  • python:
def join(l):
    """ Joins pieces with a connector recursively """
    if type(l) is list:
        if len(l) < 3:
            exit("ERROR: there aren't any pieces to join")
        c0 = join(l[0])
        c2 = join(l[2:]) if len(l) > 3 else join(l[2])
        if all([c0,c2]):
            return “%s%s%s” % (c0, l[1], c2)
        else:
            return c0 or c2
    else:
        return l
  • php:
/**
 * Function to construct a "clean" text by passing
 * an array of words and its connectors.
 */
function join_clean($words){
    if(is_array($words)){
        if(count($words) < 3)
            die("ERROR: there aren't any pieces to join");
        $c0 = join_clean($words[0]);
        if(count($words) > 3)
            $c2 = join_clean(array_slice($words, 2));
        else
            $c2 = join_clean($words[2]);
        if($c0 && $c2)
            return $c0.$words[1].$c2;
        elseif($c0)
            return $c0;
        else
            return $c2;
    }else
        return $words;
}