Skip to content

Commit

Permalink
Ensure init/cleanup of pythoncom only happens when needed
Browse files Browse the repository at this point in the history
Also ensure that we only cleanup when we are the ones to init
  • Loading branch information
Crozzers committed Nov 17, 2024
1 parent 9f7c4c1 commit f90f487
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions screen_brightness_control/windows.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import re
import threading
import time
from contextlib import contextmanager
from ctypes import Structure, WinError, byref, windll
Expand Down Expand Up @@ -39,16 +38,21 @@
@contextmanager
def _wmi_init():
'''internal function to create and return a wmi instance'''
# WMI calls don't work in new threads so we have to run this check
com_init = threading.current_thread() != threading.main_thread()
if com_init:
com_init = False
try:
yield wmi.WMI(namespace='wmi')
except Exception as e:
# WMI init will fail outside the main thread, or if CoInitialize wasn't called first
_logger.debug(f'WMI init failed ({e!r}). Calling CoInitialize and retrying')
com_init = True
if COM_MODEL is None:
pythoncom.CoInitialize()
else:
pythoncom.CoInitializeEx(COM_MODEL)

yield wmi.WMI(namespace='wmi')
yield wmi.WMI(namespace='wmi')

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

Expand Down

0 comments on commit f90f487

Please sign in to comment.