Skip to content

[Issue #390]added the client._generate._get_known_symbols #391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions comtypes/client/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from comtypes.tools import codegenerator, tlbparser

if TYPE_CHECKING:
from typing import Any, Tuple, List, Optional, Union as _UnionT
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍



logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -247,8 +247,8 @@ def _create_wrapper_module(tlib, pathname):


def _get_known_symbols():
# type: () -> dict[str, str]
known_symbols = {} # type: dict[str, str]
# type: () -> Dict[str,str]
known_symbols = {} # type: Dict[str, str]
for mod_name in (
"comtypes.persist",
"comtypes.typeinfo",
Expand All @@ -259,7 +259,7 @@ def _get_known_symbols():
):
mod = importlib.import_module(mod_name)
if hasattr(mod, "__known_symbols__"):
names = mod.__known_symbols__ # type: list[str]
names = mod.__known_symbols__ # type: List[str]
else:
names = list(mod.__dict__)
for name in names:
Expand All @@ -268,6 +268,7 @@ def _get_known_symbols():

################################################################


if __name__ == "__main__":
# When started as script, generate typelib wrapper from .tlb file.
GetModule(sys.argv[1])
57 changes: 57 additions & 0 deletions custom location/bin/clear_comtypes_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import os
import sys
import shutil

def get_next_cache_dir():
work_dir = os.getcwd()
try:
# change working directory to avoid import from local folder
# during installation process
os.chdir(os.path.dirname(sys.executable))
import comtypes.client
return comtypes.client._code_cache._find_gen_dir()
except ImportError:
return None
finally:
os.chdir(work_dir)


def _remove(directory):
shutil.rmtree(directory)
print('Removed directory "%s"' % directory)


def remove_directory(directory, silent):
if directory:
if silent:
_remove(directory)
else:
try:
confirm = raw_input('Remove comtypes cache directories? (y/n): ')
except NameError:
confirm = input('Remove comtypes cache directories? (y/n): ')
if confirm.lower() == 'y':
_remove(directory)
else:
print('Directory "%s" NOT removed' % directory)
return False
return True


if len(sys.argv) > 1 and "-y" in sys.argv[1:]:
silent = True
else:
silent = False


# First iteration may get folder with restricted rights.
# Second iteration always gets temp cache folder (writable for all).
directory = get_next_cache_dir()
removed = remove_directory(directory, silent)

if removed:
directory = get_next_cache_dir()

# do not request the second confirmation
# if the first folder was already removed
remove_directory(directory, silent=removed)
109 changes: 109 additions & 0 deletions custom location/comtypes/GUID.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from ctypes import *
import sys

if sys.version_info >= (2, 6):
def binary(obj):
return bytes(obj)
else:
def binary(obj):
return buffer(obj)

if sys.version_info >= (3, 0):
text_type = str
base_text_type = str
else:
text_type = unicode
base_text_type = basestring

BYTE = c_byte
WORD = c_ushort
DWORD = c_ulong

_ole32 = oledll.ole32

_StringFromCLSID = _ole32.StringFromCLSID
_CoTaskMemFree = windll.ole32.CoTaskMemFree
_ProgIDFromCLSID = _ole32.ProgIDFromCLSID
_CLSIDFromString = _ole32.CLSIDFromString
_CLSIDFromProgID = _ole32.CLSIDFromProgID
_CoCreateGuid = _ole32.CoCreateGuid

# Note: Comparing GUID instances by comparing their buffers
# is slightly faster than using ole32.IsEqualGUID.

class GUID(Structure):
_fields_ = [("Data1", DWORD),
("Data2", WORD),
("Data3", WORD),
("Data4", BYTE * 8)]

def __init__(self, name=None):
if name is not None:
_CLSIDFromString(text_type(name), byref(self))

def __repr__(self):
return 'GUID("%s")' % text_type(self)

def __unicode__(self):
p = c_wchar_p()
_StringFromCLSID(byref(self), byref(p))
result = p.value
_CoTaskMemFree(p)
return result
__str__ = __unicode__

def __cmp__(self, other):
if isinstance(other, GUID):
return cmp(binary(self), binary(other))
return -1

def __bool__(self):
return self != GUID_null

def __eq__(self, other):
return isinstance(other, GUID) and \
binary(self) == binary(other)

def __hash__(self):
# We make GUID instances hashable, although they are mutable.
return hash(binary(self))

def copy(self):
return GUID(text_type(self))

@classmethod
def from_progid(cls, progid):
"""Get guid from progid, ...
"""
if hasattr(progid, "_reg_clsid_"):
progid = progid._reg_clsid_
if isinstance(progid, cls):
return progid
elif isinstance(progid, base_text_type):
if progid.startswith("{"):
return cls(progid)
inst = cls()
_CLSIDFromProgID(text_type(progid), byref(inst))
return inst
else:
raise TypeError("Cannot construct guid from %r" % progid)

def as_progid(self):
"Convert a GUID into a progid"
progid = c_wchar_p()
_ProgIDFromCLSID(byref(self), byref(progid))
result = progid.value
_CoTaskMemFree(progid)
return result

@classmethod
def create_new(cls):
"Create a brand new guid"
guid = cls()
_CoCreateGuid(byref(guid))
return guid


GUID_null = GUID()

__all__ = ["GUID"]
Loading