Matplotlib和Pylab在Python CGI中无法使用
Matplotlib和Pylab在Python的CGI环境下无法使用。但是在Python的命令行界面中,这两个库的组合是可以正常工作的。以下是代码:
#!C:/Python26/python
import cgi
import cgitb
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")
3 个回答
0
看起来这是Python的ctypes
模块里的一个 bug。你需要把下面这一行注释掉:
#CFUNCTYPE(c_int)(lambda: None).
这个文件在$HOME/lib/python2.7/ctypes/__init__.py
里。
没有人真正明白这是什么意思,这其实是针对Windows的一个临时解决办法,但在Linux的cgi中会引发问题,具体可以参考这个链接:Python ctypes在PIL库的fcgi进程中出现MemoryError。
1
把
import cgitb ; cgitb.enable()
放在你脚本的最上面,运行它,然后把错误信息发给我们。没有这个,我们能提供的帮助就只有为你祈祷了。
错误信息应该很清楚,不需要额外的帮助。
顺便说一下,Python的cgi功能非常慢,实际上不适合用来处理任何复杂的事情。
0
你的代码有点不完整。现在的情况是,你把图表写到了服务器的硬盘上,但没有把它返回给浏览器。解决这个问题的一种方法是把图表保存到一个叫做StringIO的对象里,然后再把它传回去。
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()