Wednesday, January 16, 2013

How to execute python matplolib pylab from PHP

Hey people and Happy new year,

It's crazy try to execute python pylab from an script PHP. After several hours looking for a solution I got it.

If we want to exec a python script from PHP which imports the matplotlib it's necesary to add a couple of extra lines to our code.

# To import pylab
os.environ[ 'MPLCONFIGDIR' ] = '/tmp/'
import matplotlib
matplotlib.use('agg')
import pylab

Before testing your script from the server try to do it on the terminal:

sudo -u www-data php script_name.php

It works for me.

Note: If you want to download and compile matplotlib by yourself, you can download it from:

wget https://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.1.1/matplotlib-1.1.1.tar.gz

Decompress , build and execute as root the command:

python setup.py install

Hope help!



3 comments:

  1. Thanks so much! I tried so many methods, and only this tip really helped me!

    ReplyDelete
  2. Incredible!. Thank you very much. I am running Release 12.04 (precise) 32-bit and I was not able to obtain figures from a Python script called from PHP. Thank you. This was also cited in:
    http://stackoverflow.com/questions/15398920/php-and-importing-pylab

    Daniel.



    ReplyDelete
  3. Thanks man, I was struggling with an error "operation not permitted".
    MPLCONFIGDIR did the trick!

    ReplyDelete