Tôi đã tạo một tiện ích dựa trên PyQt nhỏ bằng Python để tạo biểu đồ PNG bằng cách sử dụng matplotlib khi người dùng nhấp vào nút. Mọi thứ hoạt động tốt trong vài lần nhấp chuột đầu tiên, tuy nhiên mỗi khi một hình ảnh được tạo ra, dung lượng bộ nhớ của ứng dụng tăng khoảng 120 MB, cuối cùng là hoàn toàn rơi vào Python.Bộ nhớ rò rỉ Python trong khi sử dụng PyQt và matplotlib
Làm cách nào để khôi phục bộ nhớ này sau khi tạo biểu đồ? Tôi đã bao gồm một phiên bản đơn giản của mã của tôi ở đây:
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_())
Lệnh plot.savefig ('graph.png') có vẻ là những gì đang làm xáo trộn bộ nhớ.
Tôi rất cảm kích mọi trợ giúp!
Cảm ơn! Điều này làm việc rất tốt. Tôi sẽ phải xem xét thêm chi tiết câu trả lời của bạn. –