我有一些简单的 python 代码可以生成一个实时监视器,用于查看每秒出现的数据。它使用 matplotlib 并且运行良好,只是存在内存泄漏。脚本的内存使用量在一天中缓慢上升,似乎没有限制。诚然,我对 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()