在 Python 3 CGI 中使用 matplotlib
Using matplotlib in Python 3 CGI
我一直在尝试 运行 在 CGI 脚本上使用 matplotlib,但收效甚微。我正在使用 Python3.5。
我在网上找到的大多数参考文献都显示 Python2.x 的功能。
#!/usr/bin/python
import os,sys
import cgi
import cgitb
cgitb.enable()
import matplotlib
import matplotlib.pyplot as plt
import pylab
matplotlib.use('Agg')
plt.figure()
plt.plot([1,2,3])
import io
imgData = io.BytesIO()
pylab.savefig(imgData, format='png')
imgData.seek(0)
print("Content-type: image/png")
print()
print(imgData.read())
我在 Arch Linux 上 运行ning Apache 2.4.18,我收到以下错误:
The server encountered an internal error and was unable to complete your request.
Error message:
End of script output before headers: index.py
If you think this is a server error, please contact the webmaster.
我的脚本具有执行所需的所有权限。
我们将不胜感激。
更新:我将 matplotlib.use('Agg')
移到 import matplotlib
的正下方,现在它已通过服务器 header 错误。后端较早声明,因此上面的声明无效。但是,现在我收到错误:
The image 'http://localhost' cannot be displayed since it contains errors.
如何正确渲染图像?
解决了我的问题。
以下对我有用:
#!/usr/bin/python
import os,sys
import cgi
import cgitb
cgitb.enable()
import matplotlib
matplotlib.use('Agg')
os.environ['HOME'] = '/tmp'
import matplotlib.pyplot as plt
plt.plot([1,2,3])
print("Content-type: image/png")
print()
plt.savefig(sys.stdout, format='png')
我一直在尝试 运行 在 CGI 脚本上使用 matplotlib,但收效甚微。我正在使用 Python3.5。
我在网上找到的大多数参考文献都显示 Python2.x 的功能。
#!/usr/bin/python
import os,sys
import cgi
import cgitb
cgitb.enable()
import matplotlib
import matplotlib.pyplot as plt
import pylab
matplotlib.use('Agg')
plt.figure()
plt.plot([1,2,3])
import io
imgData = io.BytesIO()
pylab.savefig(imgData, format='png')
imgData.seek(0)
print("Content-type: image/png")
print()
print(imgData.read())
我在 Arch Linux 上 运行ning Apache 2.4.18,我收到以下错误:
The server encountered an internal error and was unable to complete your request.
Error message:
End of script output before headers: index.py
If you think this is a server error, please contact the webmaster.
我的脚本具有执行所需的所有权限。
我们将不胜感激。
更新:我将 matplotlib.use('Agg')
移到 import matplotlib
的正下方,现在它已通过服务器 header 错误。后端较早声明,因此上面的声明无效。但是,现在我收到错误:
The image 'http://localhost' cannot be displayed since it contains errors.
如何正确渲染图像?
解决了我的问题。
以下对我有用:
#!/usr/bin/python
import os,sys
import cgi
import cgitb
cgitb.enable()
import matplotlib
matplotlib.use('Agg')
os.environ['HOME'] = '/tmp'
import matplotlib.pyplot as plt
plt.plot([1,2,3])
print("Content-type: image/png")
print()
plt.savefig(sys.stdout, format='png')