【问题标题】:Why am i getting "memory error" in reportlab while generating the pdf为什么我在生成pdf时在reportlab中出现“内存错误”
【发布时间】:2019-08-29 12:16:20
【问题描述】:

我一直在尝试使用reportlab 生成pdf。 当我放 4 张图片时,它可以工作。 但我只放了 5 张显示内存错误的图像。 请帮忙。

代码如下:

def plot_graph():
    plt.figure(figsize=(8, 5.25))

    stats = data.resample('D', on='DATE').count()['DATE']
    stats.plot(figsize=(12, 12))
    plt.xlabel('Dates', fontsize=16)
    plt.ylabel('Number of People', fontsize=16)
    plt.grid()

    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=300)
    buf.seek(0)

    return buf




def plot_graph1():
    plt.figure(figsize=(8, 5.25))

    stats = data.resample('D', on='DATE').count()['DATE']
    stats.plot(figsize=(12, 12))
    plt.xlabel('Dates', fontsize=16)
    plt.ylabel('Number of People', fontsize=16)
    plt.grid()

    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=300)
    buf.seek(0)

    return buf1

情节 2,3,4 也是如此。这样一共有 5 个地块。

image_buffer1 = plot_graph()
im = Image(image_buffer1, 8 * inch, 5.25 * inch)
Story.append(im)

add_text("Description of the chart.")

image_buffer1 = plot_graph1()
im2 = Image(image_buffer2, 8 * inch, 5.25 * inch)
Story.append(im2)

add_text("Description of the chart.")

情节 2,3,4 也是如此。这样一共有 5 个地块。

请帮忙。 我的代码有什么问题?

错误:

 name = _digester(rawdata+mdata)
MemoryError

【问题讨论】:

  • 嗯,原因很明显:此时,您的进程已经吃掉了所有可用内存。图像也会占用大量内存和 PDF,在生成 PDF 时,您会将所有这些以及更多加载到内存中,因此您必须非常小心如何使用内存(确保尽可能释放,尽可能从文件而不是内存中工作等)。
  • @brunodesthuilliers 您对此有什么解决方案吗?详细到执行过程?
  • @renny 在我之前的评论中,“程序”在所有字母中都有:“你必须非常小心你如何使用内存(确保你尽可能释放,从文件而不是内存工作尽可能等)”。请注意,即使那样,当然仍然是可用内存的硬限制。

标签: python pandas matplotlib pdf reportlab


【解决方案1】:

您内存不足的最可能原因是您没有关闭plt

我使用此功能在我的 PDF 中保存和绘制图表:

def save_and_draw(fig, x_img, y_img, width_img=width_img, height_img=height_img):

    imgdata = BytesIO()
    fig.savefig(imgdata, format="png")
    imgdata.seek(0)
    imgdata = ImageReader(imgdata)

    self.c.drawImage(imgdata, x_img, y_img, width_img, height_img)
    plt.close(fig)

其中一些有超过 15 个地块,一切对我来说都很好。希望对您有所帮助!

【讨论】:

  • 请查看更新后的代码。我对 plt.close() 使用了相同的代码,但它也不起作用。 P.S - 我也有同样的记忆问题
  • 您的代码中没有plt.close()。即使有,您也必须将您的数字传递给close() 函数(查看我的函数:plt.close(fig))或all 以关闭所有数字。检查here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多