Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win32 exception occurred when using pythoncom.CoUninitialize() and wmi

Tags:

python

winapi

wmi

I am trying to create a to create a function in python 3.4 that will ping a server. Currently it only needs to work on Windows (possibly XP and above).

I have found that I can use the WMI Win32_PingStatus (Reference) class to ping a server and have written the following function:

import sys

if sys.platform.startswith('win32'):
    import wmi
    import pythoncom


def ping(ip_address):
    """ Check if can ping ip address using OS ping tool"""
    if sys.platform.startswith('win32'):
        try:
            pythoncom.CoInitialize()
            c = wmi.WMI()
            status_code = c.Win32_PingStatus(address=ip_address)[0].StatusCode
            if status_code == 0:
                successful = True
            else:
                successful = False

            pythoncom.CoUninitialize()

        except wmi.x_wmi:
            # If WMI ping fails fallback
            pass

    else:
        raise NotImplementedError

    return successful

if __name__ == "__main__":
    ping("127.0.0.1")

This works as intended as it returns True when you can ping the IP and false when you can't. However every time I run it I get a series of errors at the end:

Win32 exception occurred releasing IUnknown at 0x03140980
Win32 exception occurred releasing IUnknown at 0x031635d0
Win32 exception occurred releasing IUnknown at 0x03163560 

This happens every time I run the script although the first 2 bytes of the address change each time. The last 2 bytes always stay the same.

I have tried commenting out various sections of the code and have found that if I remove pythoncom.CoUninitialize() the exceptions do not occur. I am using pythoncom.CoInitialize() and pythoncom.CoUninitialize() as I want to call the function in a thread as described here

I have tried adding print(pythoncom._GetInterfaceCount()) to see how many interfaces are present and have noticed that each time the function is run the interfaces increase by 6 and then occasionally but not often reduce however they do not reduce back down under 10 ever.

Does anyone know why this exception is occurring and what the correct way to deal with it is?

Thank you

like image 597
mpursuit Avatar asked Apr 28 '26 17:04

mpursuit


1 Answers

I think I have managed to fix the problem. It seems that you should only call pythoncom.CoInitialize() in a separate thread as pythoncom automatically calls it on the main thread http://docs.activestate.com/activepython/2.5/pywin32/pythoncom__CoInitializeEx_meth.html.

So I just check if the current thread is the main thread and if it is I don't call pythoncom.CoInitialize() and pythoncom.CoUninitialize().

like image 52
mpursuit Avatar answered May 01 '26 06:05

mpursuit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!