这个python监控cpu的小程序中 应用 了回调函数callback
add_callback 什么意思
为什么之后又要清空回调信息
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import psutil as p
POINTS =60
fig,ax = plt.subplots(2)
#一个图上画多个表https://blog.csdn.net/htuhxf/article/details/82986440
#fig,ax = plt.subplots(2,facecolor='#FF1493')#设置上下两个图、面板色。颜色的网站www.cnblogs.com/darkknightzh/p/6117528.html
fig.canvas.set_window_title(u'电脑性能(cpu、内存、网速)实时监测')#设置窗口标题
fig.canvas.toolbar.destroy()#取消工具栏
fig.canvas.callbacks.callbacks.clear()#清除回调信息
#ax为列表,分别设置
ax[0].set_ylim([0, 100])
ax[0].set_xlim([0, POINTS])
ax[0].set_autoscale_on(False)
ax[0].set_xticks([])
ax[0].set_yticks(range(0, 101, 10))
#ax[0].set_facecolor('#A9A9A9')#可设置底色,支持'black')#matplotlib颜色分层设置(表的颜色)
ax[0].grid(True)
#ax[1].set_ylim([-5, 50])#设置0线上浮
ax[1].set_ylim([-5, 50])#设置0线上浮
ax[1].set_xlim([0, POINTS])
ax[1].set_autoscale_on(False)
ax[1].set_xticks([])
#ax[1].set_yticks(range(0, 51, 10))
ax[1].set_yticks(range(0, 101, 10))#线的
ax[1].grid(True)
# 设置CPU、内存横坐标数据位
cpu = [None] * POINTS
mem=[None] * POINTS
# 设置接收字节(下载)横坐标数据位
down = [None] * POINTS
#设置第一个图
cpu_l, = ax[0].plot(range(POINTS), cpu, label='Cpu%',color = 'red')
mem_l, = ax[0].plot(range(POINTS), mem, label='Mem%')
ax[0].legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))#打标
#设置第二个图
down_l, = ax[1].plot(range(POINTS), down, label='Down(M)')
ax[1].legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))
before =p.net_io_counters().bytes_recv#获取网络字节数
def get_delta():#获取下载变化值
global before
now = p.net_io_counters().bytes_recv
delta = (now-before)/102400#变成K再除100,大致相当于多少M宽带。
before = now
return delta #返回改变量
def OnTimer(ax):
global cpu, mem, down
tmp = get_delta()#得到下载字节数的变化值
cpu_p=p.cpu_percent()#读取CPU使用百分比
cpu = cpu[1:] + [cpu_p]#加入到数据末尾
mem_p=p.virtual_memory().percent#读取内存使用百分比
mem =mem[1:] + [mem_p]#加入到数据末尾
cpu_l.set_ydata(cpu)#设置新数据
mem_l.set_ydata(mem)#设置新数据
down = down[1:] + [tmp]
down_l.set_ydata(down)#设置新数据
ax.figure.canvas.draw()#刷新画布
def start_monitor():
timer = fig.canvas.new_timer(interval=1000)#1秒刷新一次
timer.add_callback(OnTimer, ax[1])#只加一个即可
#timer.add_callback(OnTimer, ax[0])
timer.start()
plt.show()
if __name__ == '__main__':
start_monitor()