'how to get cpu stats every 15 seconds ? python [closed]

see i am using

    import psutil
    d =  psutil.cpu_percent(1.5)
    e =  psutil.cpu_percent(1.5)
    f  =  psutil.cpu_percent(1.5)
    g  =  psutil.cpu_percent(1.5)
    
    val = (d + e +f+g)/4
    print(d , e , f, g)
    print(val)

when I used interval's my import psutil was unreachable



Solution 1:[1]

Just use a while loop with 15 seconds time gap using time module.

So, it should look like this:

try:
    import psutil, time
    while True:
        d = psutil.cpu_percent(1.5)
        e = psutil.cpu_percent(1.5)
        f = psutil.cpu_percent(1.5)
        g = psutil.cpu_percent(1.5)
        
        val = (d + e + f + g)/4
        print(d, e, f, g)
        print(val)

        time.sleep(15)
except Exception as e:
    print(str(e).capitalize())
except KeyboardInterrupt:
    print("Finished!")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1