簡體   English   中英

在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上運行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.

如何正確渲染圖像?

解決了我的問題。

以下為我工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM