开发者

Matplotlib and Pylab doesn't work in Python CGI

开发者 https://www.devze.com 2023-01-02 22:03 出处:网络
Matplotlib and Pylab don\'t work in Python CGI. But the same combination is working in the Python shell.

Matplotlib and Pylab don't work in Python CGI. But the same combination is working in the Python shell. Following is the code:

#!C:/Python26/python
import cgi
import cg开发者_如何转开发itb
import sys
import os
cgitb.enable()

# set HOME environment variable to a directory the httpd server can write to
os.environ[ 'HOME' ] = '/tmp/'

import matplotlib
# chose a non-GUI backend
matplotlib.use( 'Agg' )

import pylab

#Deals with inputing data into python from the html form
form = cgi.FieldStorage()

# construct your plot
pylab.plot([1,2,3])

print "Content-Type: image/png\n"

# save the plot as a png and output directly to webserver
pylab.savefig( "test.png")


Put

import cgitb ; cgitb.enable()

at the top of your script, run it and show us the traceback. Without that the only help we can provide is to pray for you.

The traceback should be clear enough without extra help really.

An aside, Python cgi is extremely slow and not really something you can use for anything non trivial.


Your code is a little incomplete. As it stands you are writing the plot to a file on the servers hard-drive. You are not returning it to the browser. One method to do this is to save the plot to a StringIO object and then stream it back.

import cStringIO
imgData = cStringIO.StringIO()
pylab.savefig(imgData, format='png')

# rewind the data
imgData.seek(0)

print "Content-Type: image/png\n"
print

print imgData.read()


It seems this is a bug in Python ctypes module. One has to comment the line

#CFUNCTYPE(c_int)(lambda: None).

in $HOME/lib/python2.7/ctypes/__init__.py.

No one understands what that meant, it's a workaround for Windows which makes troubles in Linus cgi, see Python ctypes MemoryError in fcgi process from PIL library.

0

精彩评论

暂无评论...
验证码 换一张
取 消