中断无限运行的 Pyplot 循环
我需要实现一个实时绘图,它需要无限期地运行,直到我用按键或 cntrl C 中断它。
import matplotlib.pyplot as plt
import psutil
import time
plt.plot()
fig = plt.gcf()
fig.set_size_inches(12, 6) # width and height in inches
fig.show()
i=1
x, y = [], []
x_scale = 30
while True:
if len(x) > x_scale:
x.pop(0)
y.pop(0)
x.append(i)
y.append(psutil.cpu_percent())
plt.plot(x,y, color = 'b')
fig.canvas.draw()
plt.ylabel('CPU (%)')
plt.xlabel('TIME (ds)')
plt.xlim(left=i-x_scale, right=i)
plt.ylim(top = 100, bottom = 0)
time.sleep(.1)
i += 1
这段代码可能不是最佳的,因为我仍在学习 Matplotlib,但它正在做我想要的事情。(监控 psutils 只是暂时的。)我的问题是,即使使用 cntrl C,我也无法中断绘图。唯一有效的是 cntrl+alt+delete,在 Linux 中它会将我注销。
请问有什么建议吗?
徐拉克斯
I need to implement a real time plot which needs to run indefinitely until I interrupt it with a keypress or a cntrl C.
import matplotlib.pyplot as plt
import psutil
import time
plt.plot()
fig = plt.gcf()
fig.set_size_inches(12, 6) # width and height in inches
fig.show()
i=1
x, y = [], []
x_scale = 30
while True:
if len(x) > x_scale:
x.pop(0)
y.pop(0)
x.append(i)
y.append(psutil.cpu_percent())
plt.plot(x,y, color = 'b')
fig.canvas.draw()
plt.ylabel('CPU (%)')
plt.xlabel('TIME (ds)')
plt.xlim(left=i-x_scale, right=i)
plt.ylim(top = 100, bottom = 0)
time.sleep(.1)
i += 1
This code may not be optimal since I am still learning Matplotlib but it is doing what I want.( Monitoring psutils is only temporary.) My problem is, I am unable to interrupt the plotting even with a cntrl C. Only thing that works is cntrl+alt+delete which in Linux is logging me out.
Any suggestions please?
xuraax
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我使用了 plt.waitforbuttonpress() 而不是 time.sleep()。用于解决无响应窗口和按键中断中断问题。
我希望您看到这有帮助:
I used
plt.waitforbuttonpress()
instead oftime.sleep()
. for solving the not responding window and breaking on key interrupt.I hope you see this helpful: