【问题标题】:How to serve multiple matplotlib images from cherrypy?如何从cherrypy提供多个matplotlib图像?
【发布时间】:2018-02-16 16:47:02
【问题描述】:

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

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())

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

【问题讨论】:

    标签: python python-3.x matplotlib cherrypy


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2020-07-17
      • 2010-12-21
      • 2018-09-30
      • 2011-07-22
      • 2020-05-05
      相关资源
      最近更新 更多