you're reading...
Python, Source Code, Technology

Python – Monitor Process CPU using WMI

The following code lets us monitor a process running in windows using the WMI package designed for Python language. I have tested the same on multiple windows boxes and the results have been mostly accurate. Enjoy

import time
import wmi

wmiInterface = wmi.WMI ()

process_info = {}
while True: #Change the looping condition
  for process in wmiInterface.Win32_Process (name="NAME of the EXE"):
    id = process.ProcessID
    for p in wmiInterface.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
      n1, d1 = long (p.PercentProcessorTime), long (p.Timestamp_Sys100NS)
      n0, d0 = process_info.get (id, (0, 0))
        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)


No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: