我是python的新手,作为我正在创建的程序的一部分,我正在尝试使用WMI获取所有正在运行的进程及其当前处理器利用率的列表。我也使用线程事件调度程序每隔30秒调用一次。
import wmi
from threading import Timer
import time
c = wmi.WMI()
time_to_sleep = 30
def get_process_info():
process_info = {}
try:
for process in c.Win32_Process ():
id = process.ProcessID
for p in c.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
n1, d1 = long (p.PercentProcessorTime), long (p.Timestamp_Sys100NS)
n0, d0 = process_info.get (id, (0, 0))
try:
percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
except ZeroDivisionError:
percent_processor_time = 0.0
process_info[id] = (n1, d1)
print id, process.Caption, str(percent_processor_time)
finally:
Timer(time_to_sleep, get_process_info, ()).start()
time.sleep(time_to_sleep) #Sleep while it loops
get_process_info()
第一次运行时,它执行正常,但第二次运行它会引发错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 755, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\Administrator\workspace\WorkflowTesting\Workflow\Workflow.py", line 32, in get_process_info
for process in c.Win32_Process ():
File "C:\Python27\lib\site-packages\wmi.py", line 817, in query
return self._namespace.query (wql, self, fields)
File "C:\Python27\lib\site-packages\wmi.py", line 1009, in query
return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Python27\lib\site-packages\wmi.py", line 1003, in _raw_query
handle_com_error ()
File "C:\Python27\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
x_wmi: <x_wmi: Unexpected COM Error (-2147352567, 'Exception occurred.', (0, u'SWbemServicesEx', None, None, 0, -2147221008), None)>
答案 0 :(得分:0)
最好不使用线程来使用以下方法:
import wmi
import time
time_to_sleep = 30
c = wmi.WMI()
process_info = {}
while True:
for process in c.Win32_Process ():
id = process.ProcessID
for p in c.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
n1, d1 = long (p.PercentProcessorTime), long (p.Timestamp_Sys100NS)
n0, d0 = process_info.get (id, (0, 0))
try:
percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
except ZeroDivisionError:
percent_processor_time = 0.0
process_info[id] = (n1, d1)
print id, process.Caption, str(percent_processor_time)
time.sleep(time_to_sleep)
我不确定睡眠时间是否有其他影响,但现在它似乎运作良好。我怀疑如果我需要完成其他操作,可以在单独的线程上执行此操作吗?