简体   繁体   English

中断无限运行的 Pyplot 循环

[英]Interrupting an infinitely running Pyplot loop

I need to implement a real time plot which needs to run indefinitely until I interrupt it with a keypress or a cntrl C.我需要实现一个实时 plot,它需要无限期地运行,直到我用按键或 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.这段代码可能不是最佳的,因为我仍在学习 Matplotlib,但它正在做我想做的事。(监控 psutils 只是暂时的。)我的问题是,即使使用 cntrl C,我也无法中断绘图。唯一有效的是Linux 中的 cntrl+alt+delete 正在注销我。

Any suggestions please?有什么建议吗?

xuraax xuraax

I used plt.waitforbuttonpress() instead of time.sleep() .我使用plt.waitforbuttonpress()而不是 time.sleep( time.sleep() for solving the not responding window and breaking on key interrupt.用于解决无响应window 和按键中断中断。
I hope you see this helpful:我希望你看到这有帮助:

import matplotlib.pyplot as plt
import psutil


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)
    i += 1
    if plt.waitforbuttonpress(0.1): break # this will wait 0.1 seconds for your keypress and if pressed, it breaks out of the loop
    # and you simply can close the plot window

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM