CGIスクリプトからmatplotlibを利用

Python CGIスクリプトからmatplotlibを利用する方法。

os.environ['MPLCONFIGDIR'] = "work" # 1
import matplotlib
matplotlib.use('Agg') # 2
import pylab

pylab.plot([1, 2, 3, 4], [1, 2, 3, 4], 'o-')

import StringIO
out = StringIO.StringIO()
pylab.savefig(out, format="png")
out.seek(0)

print("Content-Type: image/png")
print("")
print(out.read())


1でwebサーバ実行ユーザが書き込みできるディレクトリを指定。


2でmatplotlibのバックエンドをAggに変更。
デフォルトのTkAgg (たぶん) だとXを利用するらしく途中でこけます。
ワークディレクトリにmatplotlibrcを置いてそちらで指定しても可です。


以下を参考にさせていただきました。
SciPy Cookbook — SciPy Cookbook documentation
Lurker - Database message source pull failure