Skip navigation.

CPU Monitor With Python And WMI

CPU Monitor With Python And WMI

Tim Golden's WMI module for Python is a lightweight wrapper around the WMI classes available for all Win32 platforms.

Windows Management Instrumentation (WMI) is Microsoft's implementation of Web-Based Enterprise Management (WBEM), an industry initiative to provide a Common Information Model (CIM) for pretty much any information about a computer system.

I will give a simple example of monitoring your local CPU using the WMI module from a Python program.


First, we can explore the WMI Win32_Processor class:

import wmi
c = wmi.WMI()
for s in c.Win32_Processor():
    print s


Output looks like this:

instance of Win32_Processor
{
    AddressWidth = 32;
    Architecture = 0;
    Availability = 3;
    Caption = "x86 Family 6 Model 13 Stepping 6";
    CpuStatus = 1;
    CreationClassName = "Win32_Processor";
    CurrentClockSpeed = 1794;
    CurrentVoltage = 33;
    DataWidth = 32;
    Description = "x86 Family 6 Model 13 Stepping 6";
    DeviceID = "CPU0";
    ExtClock = 133;
    Family = 2;
    L2CacheSize = 2048;
    Level = 6;
    LoadPercentage = 6;
    Manufacturer = "GenuineIntel";
    MaxClockSpeed = 1794;
    Name = "        Intel(R) Pentium(R) M processor 1.80GHz";
    PowerManagementSupported = FALSE;
    ProcessorId = "AFE9F9BF000006D6";
    ProcessorType = 3;
    Revision = 3334;
    Role = "CPU";
    SocketDesignation = "Microprocessor";
    Status = "OK";
    StatusInfo = 3;
    Stepping = "6";
    SystemCreationClassName = "Win32_ComputerSystem";
    SystemName = "GOLDB";
    UpgradeMethod = 6;
    Version = "Model 13, Stepping 6";
    VoltageCaps = 2;
};



Here I use it in a script that prints CPU utilization every 5 seconds:

import wmi
import time

c = wmi.WMI()
while True:
    for cpu in c.Win32_Processor():
        timestamp = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime())
        print '%s | Utilization: %s: %d %%' % (timestamp, cpu.DeviceID, cpu.LoadPercentage)
        time.sleep(5)


      
Output looks like this:

Sun, 12 Nov 2006 19:26:25 | Utilization: CPU0: 4 %
Sun, 12 Nov 2006 19:26:31 | Utilization: CPU0: 8 %
Sun, 12 Nov 2006 19:26:37 | Utilization: CPU0: 1 %
Sun, 12 Nov 2006 19:26:43 | Utilization: CPU0: 6 %
Sun, 12 Nov 2006 19:26:49 | Utilization: CPU0: 13 %