私は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()
最初の実行では問題なく実行されますが、2 回目の実行ではエラーがスローされます。
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)>