如何从 cherrypy 提供多个 matplotlib 图像?

How to serve multiple matplotlib images from cherrypy?

我有以下 HelloWorld 项目,使用 Python 3 和提供 2 个 matplotlib 图像的 cherrypy:

import cherrypy
import matplotlib.pyplot as plt
import numpy as np

from io import BytesIO


class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        output = """
        Hello World!
        <img src="image1.png" width="640", height="480" border="0" />

        <img src="image2.png" width="640", height="480" border="0" />
        """
        return output

    @cherrypy.expose
    def image1_png(self):
        img = BytesIO()
        self.plot(img)
        img.seek(0)
        retobj = cherrypy.lib.static.serve_fileobj(img, content_type='png', name='image1.png')
        return retobj

    @cherrypy.expose
    def image2_png(self):
        img = BytesIO()
        self.plot(img)
        img.seek(0)
        retobj = cherrypy.lib.static.serve_fileobj(img, content_type='png', name='image2.png')
        return retobj

    def plot(self, image):
        sampleData = np.random.normal(size=100)
        plt.hist(sampleData)
        plt.savefig(image, format='png')

if __name__ == '__main__':
    cherrypy.quickstart(HelloWorld())

仅调用其中一张图片(通过注释掉另一张图片)工作得很好,但调用两者都不起作用。知道如何解决这个问题吗?

原来这是 matplotlib 后端 tkinter 的线程问题。通过 matplotlib.use('agg') 手动更改后端修复了它。请注意,必须在导入 matplotlib.pyplot.

之前放置该代码段