Unable to call WMI from threads in Python

I am trying to use the WMI library for a few very simple queries:

  • Service status
  • Number of Processes
  • Free disk space

There are no problems until I start introducing streams.

My first attempt consisted of a class (rules) derived from threading.Threadand called another class (Check) that made WMI calls.

To overcome threading issues, I used the library pythoncomto initialize and uninitialize at the beginning and at the end of a WMI request. Here's how it looked:

class Process(Check):

    def __init__(self, process_name, expected_instances=1):
        self.expected_instances = expected_instances
        self.process_name = process_name


    def run(self):
        import wmi, pythoncom
        pythoncom.CoInitialize()
        try:
            self.wmi_process = wmi.WMI().Win32_Process
            process_count = len(self.wmi_process(name=self.process_name))

            if process_count == self.expected_instances:
                return result.Success('Found {0} {1} processes'.format(process_count, self.process_name))
            else:
                return result.Failure('Found {0} {1} processes, expected {2}'.format(process_count, self.process_name, self.expected_instances))
        finally:
            pythoncom.CoUninitialize()

This worked, but still lead to an error Win32 exception occurred releasing IUnknownwhen exiting the main process.

, SO, WMI , , .

class WMIService:

    __lock = threading.Lock()

    def __init__(self):
        log.debug('Initializing WMI')
        pythoncom.CoInitialize()
        self.wmi = wmi.WMI()
        self.wmi_process = self.wmi.Win32_Process
        self.wmi_service = self.wmi.Win32_Service
        self.wmi_disk = self.wmi.Win32_LogicalDisk

    def get_process_count(self, process_name):
        with self.__lock:
            log.debug('Retrieving information for process "{0}"'.format(process_name))
            return len(self.wmi_process(name=process_name))

, WMI , (, , ).

, Python , get_process_count() . , .

Traceback (most recent call last):
  File "C:\Users\Admin\pyEnvs\pyWatch\lib\site-packages\wmi.py", line 1001, in _raw_query
    return self._namespace.ExecQuery (strQuery=wql, iFlags=flags)
  File "<COMObject winmgmts:>", line 3, in ExecQuery
  File "C:\Python33\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
    result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', None, None, 0, -2147221008), None)

, , WMI . , - WMI WMIC, , .

+4

Source: https://habr.com/ru/post/1532068/


All Articles