我有一些簡單的python代碼,可以爲每秒查看數據而生成實時監視器。它使用matplotlib,工作得很好,除了有內存泄漏。腳本的內存使用情況在一天內緩慢上升,似乎沒有限制。我承認編程python是新手,所以想知道是否有人能看到我正在做的事情,顯然是很糟糕的。預先感謝您的幫助。Python實時繪圖內存泄漏
import time
import numpy as np
import matplotlib
from matplotlib import figure
import matplotlib.pyplot as plt
import pylab as p
import os
import subprocess as sp
from subprocess import Popen, PIPE
def main():
#####Initialize the plot#####
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1,axisbg='black') #Set up basic plot attributes
ax1.set_title('Blip Current vs. Time',color='blue')
ax1.set_xlabel('Time (hrs)',color='blue')
ax1.set_ylabel('Blip Current',color='blue')
for t in ax1.xaxis.get_ticklines(): t.set_color('yellow')
for t in ax1.xaxis.get_ticklabels(): t.set_color('yellow')
for t in ax1.yaxis.get_ticklines(): t.set_color('white')
for t in ax1.yaxis.get_ticklabels(): t.set_color('purple')
plt.ion() #Set interactive mode
plt.show(False) #Set to false so that the code doesn't stop here
i=0 #initialize counter variable (this will help me to limit the number of points displayed on graph
###Update the plot continuously###
while True: #This is a cheap trick to keep updating the plot, i.e. create a real time data monitor
blip=Popen('adoIf -vo -6 lxf.blip_b3 dataBarM', shell=True, stdout=PIPE).communicate()[0] #Get data to plot
hr=float(time.strftime('%H'))
mins=time.strftime('%M')
secs=time.strftime('%S')
secadj=float(secs)/3600
minadj=float(mins)/60
currenttime=float(hr+minadj+secadj) #Put time into format for easier plotting, i.e. 21.50 for 9:30 pm
if currenttime >= 0 and currenttime < 0.22: #Set x range properly when rolling over to midnight
xmin=0
xmax=currenttime+.01
else:
xmin=currenttime-.22 #Limit data to be displayed, only care about recent past
xmax=currenttime+.01
try:
blip =float(blip) #This throws an error if for some reason the data wasn't received at the top of the while statement
except ValueError:
blip=0.0
if i>300: #Limit displayed points to save memory (hopefully...)
del ax1.lines[0] #After 300 points, start deleting the first point each time
else:
i +=1
if blip > 6: #Plot green points if current is above threshold
ax1.plot(currenttime,blip,marker='o', linestyle='--',c='g')
else: #Plot red points if current has fallen off
ax1.plot(currenttime,blip,marker='o', linestyle='--',c='r')
plt.axis([xmin,xmax,None,None]) #Set xmin/xmax to limit displayed data to a reasonable window
plt.draw()
time.sleep(2) #Update every 2 seconds
if __name__=='__main__':
print 'Starting Monitor'
main()
你爲什麼要使用一個字符串(使用
plt.ion()
不推薦用於複雜的腳本。)''的true''而不是布爾TRUE;? – user2357112因爲我是新手。謝謝,我改變了它。但我懷疑這與我的記憶問題無關。 – crownjbl
你在Linux,Windows,Mac上運行嗎?子進程處理對每個處理都有點不同。 – ixe013