我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用pywintypes.IID。
def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""): if win32gui.UNICODE: # This really means "is py3k?" - so not accepting bytes is OK if not isinstance(name, unicode): raise TypeError("Must provide unicode for the name") name = name.encode('unicode-internal') else: # py2k was passed a unicode object - encode as mbcs. if isinstance(name, unicode): name = name.encode('mbcs') # 16 bytes for the IID followed by \0 term'd string. rest_fmt = "16s%ds" % len(name) # _make_memory(iid) hoops necessary to get the raw IID bytes. rest_data = (_make_memory(pywintypes.IID(classguid)), name) return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data) # An object returned by UnpackDEV_BROADCAST.
def GetModuleForProgID(progid): """Get a Python module for a Program ID Given a Program ID, return a Python module which contains the class which wraps the COM object. Returns the Python module, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application") """ try: iid = pywintypes.IID(progid) except pywintypes.com_error: return None return GetModuleForCLSID(iid)
def GetModuleForTypelib(typelibCLSID, lcid, major, minor): """Get a Python module for a type library ID Given the CLSID of a typelibrary, return an imported Python module, else None Params typelibCLSID -- IID of the type library. major -- Integer major version. minor -- Integer minor version lcid -- Integer LCID for the library. """ modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor) mod = _GetModule(modName) # If the import worked, it doesn't mean we have actually added this # module to our cache though - check that here. if "_in_gencache_" not in mod.__dict__: AddModuleToCache(typelibCLSID, lcid, major, minor) assert "_in_gencache_" in mod.__dict__ return mod
def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = bForDemandDefault, bBuildHidden = 1): """Generate support for a type library. Given the IID, LCID and version information for a type library, generate and import the necessary support files. Returns the Python module. No exceptions are caught. Params typelibCLSID -- IID of the type library. major -- Integer major version. minor -- Integer minor version. lcid -- Integer LCID for the library. progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar. """ if bGUIProgress is not None: print "The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete." import makepy try: makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden) except pywintypes.com_error: return None return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""): if win32gui.UNICODE: # This really means "is py3k?" - so not accepting bytes is OK if not isinstance(name, str): raise TypeError("Must provide unicode for the name") name = name.encode('unicode-internal') else: # py2k was passed a unicode object - encode as mbcs. if isinstance(name, str): name = name.encode('mbcs') # 16 bytes for the IID followed by \0 term'd string. rest_fmt = "16s%ds" % len(name) # _make_memory(iid) hoops necessary to get the raw IID bytes. rest_data = (_make_memory(pywintypes.IID(classguid)), name) return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data) # An object returned by UnpackDEV_BROADCAST.
def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = bForDemandDefault, bBuildHidden = 1): """Generate support for a type library. Given the IID, LCID and version information for a type library, generate and import the necessary support files. Returns the Python module. No exceptions are caught. Params typelibCLSID -- IID of the type library. major -- Integer major version. minor -- Integer minor version. lcid -- Integer LCID for the library. progressInstance -- Instance to use as progress indicator, or None to use the GUI progress bar. """ if bGUIProgress is not None: print("The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete.") from . import makepy try: makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden) except pywintypes.com_error: return None return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
def UnpackDEV_BROADCAST(lparam): if lparam == 0: return None hdr_format = "iii" hdr_size = struct.calcsize(hdr_format) hdr_buf = win32gui.PyGetMemory(lparam, hdr_size) size, devtype, reserved = struct.unpack("iii", hdr_buf) # Due to x64 alignment issues, we need to use the full format string over # the entire buffer. ie, on x64: # calcsize('iiiP') != calcsize('iii')+calcsize('P') buf = win32gui.PyGetMemory(lparam, size) extra = x = {} if devtype == win32con.DBT_DEVTYP_HANDLE: # 2 handles, a GUID, a LONG and possibly an array following... fmt = hdr_format + "PP16sl" _, _, _, x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \ struct.unpack(fmt, buf[:struct.calcsize(fmt)]) x['eventguid'] = pywintypes.IID(guid_bytes, True) elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE: fmt = hdr_format + "16s" _, _, _, guid_bytes = struct.unpack(fmt, buf[:struct.calcsize(fmt)]) x['classguid'] = pywintypes.IID(guid_bytes, True) x['name'] = win32gui.PyGetString(lparam + struct.calcsize(fmt)) elif devtype == win32con.DBT_DEVTYP_VOLUME: # int mask and flags fmt = hdr_format + "II" _, _, _, x['unitmask'], x['flags'] = struct.unpack(fmt, buf[:struct.calcsize(fmt)]) else: raise NotImplementedError("unknown device type %d" % (devtype,)) return DEV_BROADCAST_INFO(devtype, **extra)
def GetClassForProgID(progid): """Get a Python class for a Program ID Given a Program ID, return a Python class which wraps the COM object Returns the Python class, or None if no module is available. Params progid -- A COM ProgramID or IID (eg, "Word.Application") """ clsid = pywintypes.IID(progid) # This auto-converts named to IDs. return GetClassForCLSID(clsid)
def CastTo(ob, target): """'Cast' a COM object to another interface""" # todo - should support target being an IID if hasattr(target, "index"): # string like # for now, we assume makepy for this to work. if "CLSID" not in ob.__class__.__dict__: # Eeek - no makepy support - try and build it. ob = gencache.EnsureDispatch(ob) if "CLSID" not in ob.__class__.__dict__: raise ValueError("Must be a makepy-able object for this to work") clsid = ob.CLSID # Lots of hoops to support "demand-build" - ie, generating # code for an interface first time it is used. We assume the # interface name exists in the same library as the object. # This is generally the case - only referenced typelibs may be # a problem, and we can handle that later. Maybe <wink> # So get the generated module for the library itself, then # find the interface CLSID there. mod = gencache.GetModuleForCLSID(clsid) # Get the 'root' module. mod = gencache.GetModuleForTypelib(mod.CLSID, mod.LCID, mod.MajorVersion, mod.MinorVersion) # Find the CLSID of the target target_clsid = mod.NamesToIIDMap.get(target) if target_clsid is None: raise ValueError("The interface name '%s' does not appear in the " \ "same library as object '%r'" % (target, ob)) mod = gencache.GetModuleForCLSID(target_clsid) target_class = getattr(mod, target) # resolve coclass to interface target_class = getattr(target_class, "default_interface", target_class) return target_class(ob) # auto QI magic happens raise ValueError
def _guid_from_buffer(b): return pywintypes.IID(b, True)
def testGUID(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEquals(iid, iid2) self.assertRaises(ValueError, pywintypes.IID, str2bytes('00'), True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer
def testGUIDRichCmp(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) self.failIf(s==None) self.failIf(None==s) self.failUnless(s!=None) self.failUnless(None!=s) if sys.version_info > (3,0): self.assertRaises(TypeError, operator.gt, None, s) self.assertRaises(TypeError, operator.gt, s, None) self.assertRaises(TypeError, operator.lt, None, s) self.assertRaises(TypeError, operator.lt, s, None)
def GetGeneratedInfos(): zip_pos = win32com.__gen_path__.find(".zip\\") if zip_pos >= 0: import zipfile zip_file = win32com.__gen_path__[:zip_pos+4] zip_path = win32com.__gen_path__[zip_pos+5:].replace("\\", "/") zf = zipfile.ZipFile(zip_file) infos = {} for n in zf.namelist(): if not n.startswith(zip_path): continue base = n[len(zip_path)+1:].split("/")[0] try: iid, lcid, major, minor = base.split("x") lcid = int(lcid) major = int(major) minor = int(minor) iid = pywintypes.IID("{" + iid + "}") except ValueError: continue except pywintypes.com_error: # invalid IID continue infos[(iid, lcid, major, minor)] = 1 zf.close() return list(infos.keys()) else: # on the file system files = glob.glob(win32com.__gen_path__+ "\\*") ret = [] for file in files: if not os.path.isdir(file) and not os.path.splitext(file)[1]==".py": continue name = os.path.splitext(os.path.split(file)[1])[0] try: iid, lcid, major, minor = name.split("x") iid = pywintypes.IID("{" + iid + "}") lcid = int(lcid) major = int(major) minor = int(minor) except ValueError: continue except pywintypes.com_error: # invalid IID continue ret.append((iid, lcid, major, minor)) return ret
def getevents(clsid): """Determine the default outgoing interface for a class, given either a clsid or progid. It returns a class - you can conveniently derive your own handler from this class and implement the appropriate methods. This method relies on the classes produced by makepy. You must use either makepy or the gencache module to ensure that the appropriate support classes have been generated for the com server that you will be handling events from. Beware of COM circular references. When the Events class is connected to the COM object, the COM object itself keeps a reference to the Python events class. Thus, neither the Events instance or the COM object will ever die by themselves. The 'close' method on the events instance must be called to break this chain and allow standard Python collection rules to manage object lifetimes. Note that DispatchWithEvents() does work around this problem by the use of a proxy object, but if you use the getevents() function yourself, you must make your own arrangements to manage this circular reference issue. Beware of creating Python circular references: this will happen if your handler has a reference to an object that has a reference back to the event source. Call the 'close' method to break the chain. Example: >>>win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}',0,1,1) <module 'win32com.gen_py..... >>> >>> class InternetExplorerEvents(win32com.client.getevents("InternetExplorer.Application.1")): ... def OnVisible(self, Visible): ... print "Visibility changed: ", Visible ... >>> >>> ie=win32com.client.Dispatch("InternetExplorer.Application.1") >>> events=InternetExplorerEvents(ie) >>> ie.Visible=1 Visibility changed: 1 >>> """ # find clsid given progid or clsid clsid=str(pywintypes.IID(clsid)) # return default outgoing interface for that class klass = gencache.GetClassForCLSID(clsid) try: return klass.default_source except AttributeError: # See if we have a coclass for the interfaces. try: return gencache.GetClassForCLSID(klass.coclass_clsid).default_source except AttributeError: return None # A Record object, as used by the COM struct support