python How to watch for Win32_Processor LoadPercentage change in wmi?

2.1k Views Asked by At

How do I watch for a LoadPercentage change event using the Win32_Processor class?

import wmi
c= wmi.WMI()
x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]

Where should the watch for() method be applied so that I can know if the CPU usage has dropped to less than say 80%?

Thanks. Siva

2

There are 2 best solutions below

1
On BEST ANSWER

I'm not sure what you mean by for() method, but you can just put that in a loop:

kMaxLoad = 80
while True:
    x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
    if max(x) < kMaxLoad:
        break
print "okay, load is under %i" % kMaxLoad
0
On

I don't use that library, but here is an example query:

from win32com.client import Moniker

wmi = Moniker('winmgmts:')
events = wmi.ExecNotificationQuery("Select * From __InstanceModificationEvent "
                                   "Within 1 "
                                   "Where TargetInstance Isa 'Win32_Processor' "
                                   "And TargetInstance.LoadPercentage > 10")

processor = events.NextEvent().TargetInstance

print processor.LoadPercentage

You could also try to use one of the perf WMI classes instead of Win32_Processor.