2016-01-11 104 views
0

使用matplotlib我一直在努力,但收效甚微運行CGI腳本matplotlib。我正在使用Python3.5。在Python 3 CGI

我在網上找到的大多數參考文獻都顯示了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的運行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之下,現在它已經超過了服務器頭錯誤。後端得到更早的聲明,因此上面的聲明不起作用。但是,現在我收到錯誤:

The image 'http://localhost' cannot be displayed since it contains errors. 

如何正確渲染圖像?

+0

你引用'pylab'不導入它。 – jpcgt

+0

導入Pylab,仍然收到相同的錯誤。 – doberoi96

+0

當你絕對正確的,這似乎並不在這裏是主要的問題,因爲它是不將其更改爲「圖像/ PNG」甚至工作。 – doberoi96

回答

0

解決我的問題。

以下是爲我工作:

#!/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')