python 如何在WMI中监控Win32_Processor LoadPercentage的变化?

1 投票
2 回答
2132 浏览
提问于 2025-04-16 12:17

我想知道如何使用Win32_Processor类来监测LoadPercentage的变化事件。

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

我应该在哪里使用watch for()这个方法,这样我就能知道CPU的使用率是否降到了80%以下?

谢谢。
Siva

2 个回答

1

我不太使用那个库,不过这里有一个查询的例子:

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

你也可以试试用一些性能相关的 WMI 类,别用 Win32_Processor。

1

我不太明白你说的 for() 方法是什么意思,不过你可以把它放在一个循环里:

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

撰写回答