1

I've been trying to run matplotlib on CGI scripts with little success. I'm using Python3.5.

Most of the references I found online show functionality for 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())

I am running Apache 2.4.18 on Arch Linux, and I get the following error:

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. 

My script has all required permissions to execute.

Any help will be appreciated.

UPDATE: I moved matplotlib.use('Agg') right beneath import matplotlib and now it gets past the server header error. The backend was getting declared earlier, hence the statement above has no effect. However, now I get the error:

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

How can I correctly render images?

4
  • You are referencing pylab without importing it. Commented Jan 11, 2016 at 23:16
  • Imported Pylab, still getting the same error. Commented Jan 12, 2016 at 8:46
  • While you're absolutely correct, that doesn't seem to be the primary problem here since it isn't working even on changing it to 'image/png'. Commented Jan 12, 2016 at 11:58
  • Did you run this in a terminal? Instead of using print at the end, write the data to a file and then open it in the browser. See if that is okay. Commented Jan 12, 2016 at 14:42

1 Answer 1

1

Solved my problem.

The following is working for me:

#!/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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.