0

I have code as below which runs in a thread for every 60sec.

import wmi
import threading

CPU_DATA = {}

class CpuCollector(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.sleep_time = 60
        self.conn = wmi.WMI()

    def run(self):
        try:
            cpu_info_wql = "SELECT LoadPercentage,CurrentClockSpeed,MaxClockSpeed,NumberOfCores FROM Win32_Processor WHERE ProcessorType = 3"
            while True:
                cpu_info = self.conn.query(cpu_info_wql)[0]
                CPU_DATA['cpu.used_perc'] = long(cpu_info.LoadPercentage)
                time.sleep(self.sleep_time)
        except Exception as e:
            LOG.exception('Exception occured: %s' % e)
            raise e

cpu_collector = CpuCollector()
cpu_collector.start()

I am getting the following error.

Exception occured: <x_wmi: Unexpected COM Error (-2147352567, 'Exception occurred.', (0, u'SWbemServicesEx', None, None, 0, -2147221008), None)>

What is it that i am doing wrong here? My conn objects prints fine when i try to extract data (like dir(self.conn)) from it.

Chetan
  • 1,217
  • 2
  • 13
  • 27

1 Answers1

0

This solved the problem.

import wmi
import threading
import pythoncom

CPU_DATA = {}

class CpuCollector(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.sleep_time = 60
        self.conn = wmi.WMI()

    def run(self):
        try:
            pythoncom.CoInitialize()
            self.mymethod()            
        except Exception as e:
            LOG.exception('Exception occured: %s' % e)
            raise e

    def my method(self):
        cpu_info_wql = "SELECT LoadPercentage,CurrentClockSpeed,MaxClockSpeed,NumberOfCores FROM Win32_Processor WHERE ProcessorType = 3"
        while True:
            cpu_info = self.conn.query(cpu_info_wql)[0]
            CPU_DATA['cpu.used_perc'] = long(cpu_info.LoadPercentage)
            time.sleep(self.sleep_time)

cpu_collector = CpuCollector()
cpu_collector.start()
Chetan
  • 1,217
  • 2
  • 13
  • 27