Skip to content

Commit f90f487

Browse files
committed
Ensure init/cleanup of pythoncom only happens when needed
Also ensure that we only cleanup when we are the ones to init
1 parent 9f7c4c1 commit f90f487

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

screen_brightness_control/windows.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import logging
22
import re
3-
import threading
43
import time
54
from contextlib import contextmanager
65
from ctypes import Structure, WinError, byref, windll
@@ -39,16 +38,21 @@
3938
@contextmanager
4039
def _wmi_init():
4140
'''internal function to create and return a wmi instance'''
42-
# WMI calls don't work in new threads so we have to run this check
43-
com_init = threading.current_thread() != threading.main_thread()
44-
if com_init:
41+
com_init = False
42+
try:
43+
yield wmi.WMI(namespace='wmi')
44+
except Exception as e:
45+
# WMI init will fail outside the main thread, or if CoInitialize wasn't called first
46+
_logger.debug(f'WMI init failed ({e!r}). Calling CoInitialize and retrying')
47+
com_init = True
4548
if COM_MODEL is None:
4649
pythoncom.CoInitialize()
4750
else:
4851
pythoncom.CoInitializeEx(COM_MODEL)
4952

50-
yield wmi.WMI(namespace='wmi')
53+
yield wmi.WMI(namespace='wmi')
5154

55+
# only uninitialise if we initialised. Avoid cleaning up resources being used by another library
5256
if com_init:
5357
pythoncom.CoUninitialize()
5458

0 commit comments

Comments
 (0)