1import logging
2import threading
3
4try:
5    import pythoncom
6
7    HAS_LIBS = True
8except ImportError:
9    HAS_LIBS = False
10
11log = logging.getLogger(__name__)
12
13
14def __virtual__():
15    """
16    Only load if required libraries exist
17    """
18    if not HAS_LIBS:
19        return False
20    else:
21        return True
22
23
24class Com:
25    def __init__(self):
26        self.need_com_init = not self._is_main_thread()
27
28    def _is_main_thread(self):
29        return threading.current_thread().name == "MainThread"
30
31    def __enter__(self):
32        if self.need_com_init:
33            log.debug("Initializing COM library")
34            pythoncom.CoInitialize()
35
36    def __exit__(self, exc_type, exc_value, traceback):
37        if self.need_com_init:
38            log.debug("Uninitializing COM library")
39            pythoncom.CoUninitialize()
40