本文介绍了运行时错误:保存并随后关闭 pyplot 图时,底层 C/C++ 对象已被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个 python 错误,我已经尝试解决了好几天了.我的程序创建图形,保存并关闭它们,除此错误外都可以正常工作.通常它不会妨碍保存过程,但有时保存时图片会丢失下部.奇怪的是,这只会在循环到达 savefig 方法时每秒发生一次,这是我的代码:

I ran into a python error that i have been trying to solve for several days now.My program creates figures, saves and closes them which works fine except for this error. Usually it does not hinder the saving process but sometimes a picture is missing the lower part when saved. The odd thing is that this only happens every second time the loop reaches the savefig method, here is my code:

for num in np.arange(file_number):
    plt.figure('abc' + str(num),figsize=(22,12),dpi=100)
    #some plots are added to the figure
    print 1
    plt.savefig(os.path.join(savepath,filename),dpi=100)
    print 2
    plt.close()
    print 3

我使用打印命令查看错误发生的位置.这是 spyder 的控制台输出:

I use the print commands to see where the error occurs. Here is the console output of spyder:

Reading file1.file
1
2
3
Reading file2.file
1
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 151, in <lambda>
    lambda: self.close_event())
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1564, in close_event
    self.callbacks.process(s, event)
RuntimeError: underlying C/C++ object has been deleted
2
3
Reading file3.file
1
2
3
Reading file4.file
1
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 151, in <lambda>
    lambda: self.close_event())
  File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1564, in close_event
    self.callbacks.process(s, event)
RuntimeError: underlying C/C++ object has been deleted
2
3

据我所知,在保存图形时(每第二次)已经发生错误,尽管如果我省略 close() 命令它可以正常工作.在这种情况下,我的 RAM 在大约 70 个文件后被填满,有时我需要评估数百个.这就是为什么我需要包含 close() 命令或类似的东西.如果你解决了这个问题(或者改进了我的程序,我想我保存和关闭的方式可能会被认为是丑陋的)请帮助我.

To my understanding, the error already occurs while saving the figure (every second time), although it works fine if i omit the close() command. In that case, my RAM is filled after about 70 files and sometimes i need to evaluate a couple of hundreds. That's why i need to include the close() command or something similar.If you solve this (or improve my programing, i guess the way i did this saving and closing might be considered ugly) please help me.

推荐答案

把后端改成其他选项怎么样?例如:

How about change the backend to other options? For example:

import matplotlib as mpl
mpl.use( "agg" )

from matplotlib import pyplot as plt
import numpy as np

print plt.get_backend()

file_number = 100
for num in np.arange(file_number):
    plt.figure('abc' + str(num),figsize=(22,12),dpi=100)
    #some plots are added to the figure
    print 1
    plt.savefig("%d.png" % num,dpi=100)
    print 2
    plt.close()
    print 3

这篇关于运行时错误:保存并随后关闭 pyplot 图时,底层 C/C++ 对象已被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 04:00