문제

사용자가 버튼을 클릭 할 때 matplotlib를 사용하여 PNG 그래프를 생성하는 작은 PYQT 기반 유틸리티를 만들었습니다. 처음 몇 번의 클릭 중에 모든 것이 잘 작동하지만 이미지가 생성 될 때마다 응용 프로그램의 메모리 풋 프린트는 약 120MB로 증가하여 결국 파이썬이 모두 충돌합니다.

그래프가 생성 된 후이 메모리를 어떻게 복구 할 수 있습니까? 여기에 내 코드의 단순화 된 버전이 포함되어 있습니다.

import datetime as dt
from datetime import datetime 
import os
import gc
# For Graphing
import matplotlib
from pylab import figure, show, savefig
from matplotlib import figure as matfigure
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter, DayLocator
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plot
import matplotlib.ticker as ticker
# For GUI
import sys
from PyQt4 import QtGui, QtCore

class HyperGraph(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('Title')
        self.create_widgets()

    def create_widgets(self):
        grid = QtGui.QGridLayout()
        self.generate_button = QtGui.QPushButton("Generate Graph", self)
        grid.addWidget(self.generate_button, 1, 1)
        QtCore.QObject.connect(self.generate_button, QtCore.SIGNAL("clicked()"), self.generate_graph)

    def generate_graph(self):
        try:
            fig = figure()
            ax = fig.add_axes([1,1,1,1])

            # set title
            ax.set_title('Title')

            # configure x axis
            plot.xlim(dt.date.today() - dt.timedelta(days=180), dt.date.today())
            ax.set_xlabel('Date')
            fig.set_figwidth(100)

            # configure y axis
            plot.ylim(0, 200)
            ax.set_ylabel('Price')
            fig.set_figheight(30)

            # export the graph to a png file
            plot.savefig('graph.png')

        except:
            print 'Error'

        plot.close(fig)
        gc.collect()

app = QtGui.QApplication(sys.argv)
hyper_graph = HyperGraph()
hyper_graph.show()
sys.exit(app.exec_())

plot.savefig ( 'Graph.png') 명령은 메모리를 올리는 것 같습니다.

나는 어떤 도움을 주셔서 대단히 감사합니다!

도움이 되었습니까?

해결책

일부 백엔드는 메모리를 유출하는 것 같습니다. 백엔드를 명시 적으로 설정하십시오

import matplotlib
matplotlib.use('Agg') # before import pylab
import pylab

다른 팁

PYPLOT 인터페이스는 대화식 사용이 쉽지만 응용 프로그램에 임베딩하기위한 객체 지향 API가 더 좋습니다. 예를 들어, PyPlot은 생성 한 모든 수치를 추적합니다. 당신의 plot.close(figure) ~해야 한다 그들을 제거하지만 어쩌면 실행되지 않을 수도 있습니다. 내부에 넣으십시오. finally 또는 동일한 그림 객체를 재사용합니다.

보다 이 예 객체 지향 API를 사용하여 PYQT4 애플리케이션에 MATPLOTLIB를 포함시킵니다. 더 많은 작업이지만 모든 것이 명백하기 때문에 PyPlot가하는 비하인드 자동화에서 메모리 누출을 얻지 않아야합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top