def _CreateInstance_(self, clsid, reqIID): """Creates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@) """ try: classSpec = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regSpec % clsid) except win32api.error: raise error( "The object is not correctly registered - %s key can not be read" % (regSpec % clsid)) myob = call_func(classSpec) self._wrap_(myob) try: return pythoncom.WrapObject(self, reqIID) except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, arg) = xxx_todo_changeme.args from win32com.util import IIDToInterfaceName desc = "The object '%r' was created, but does not support the " \ "interface '%s'(%s): %s" \ % (myob, IIDToInterfaceName(reqIID), reqIID, desc) raise pythoncom.com_error(hr, desc, exc, arg)
def _find_localserver_exe(mustfind): if not sys.platform.startswith("win32"): return sys.executable if pythoncom.__file__.find("_d") < 0: exeBaseName = "pythonw.exe" else: exeBaseName = "pythonw_d.exe" # First see if in the same directory as this .EXE exeName = os.path.join(os.path.split(sys.executable)[0], exeBaseName) if not os.path.exists(exeName): # See if in our sys.prefix directory exeName = os.path.join(sys.prefix, exeBaseName) if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) if "64 bit" in sys.version: exeName = os.path.join(sys.prefix, "PCbuild", "amd64", exeBaseName) else: exeName = os.path.join(sys.prefix, "PCbuild", exeBaseName) if not os.path.exists(exeName): # See if the registry has some info. try: key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, key) exeName = os.path.join(path, exeBaseName) except (AttributeError, win32api.error): pass if not os.path.exists(exeName): if mustfind: raise RuntimeError("Can not locate the program '%s'" % exeBaseName) return None return exeName
def _get_string(path, base=win32con.HKEY_CLASSES_ROOT): "Get a string value from the registry." try: return win32api.RegQueryValue(base, path) except win32api.error: return None
def CheckPythonPaths(verbose): if verbose: print("Python Paths:") # Check the core path if verbose: print("\tCore Path:", end=' ') try: appPath = win32api.RegQueryValue( regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath") except win32api.error as exc: print("** does not exist - ", exc.strerror) problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ) try: keyNo = 0 while True: try: appName = win32api.RegEnumKey(key, keyNo) appPath = win32api.RegQueryValue(key, appName) if verbose: print("\t" + appName + ":", end=' ') if appPath: problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) else: if verbose: print("(empty)") keyNo = keyNo + 1 except win32api.error: break finally: win32api.RegCloseKey(key)
def EnumTlbs(excludeFlags=0): """Return a list of TypelibSpec objects, one for each registered library. """ key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "Typelib") iids = EnumKeys(key) results = [] for iid, crap in iids: try: key2 = win32api.RegOpenKey(key, str(iid)) except win32api.error: # A few good reasons for this, including "access denied". continue for version, tlbdesc in EnumKeys(key2): major_minor = version.split('.', 1) if len(major_minor) < 2: major_minor.append('0') # For some reason, this code used to assume the values were hex. # This seems to not be true - particularly for CDO 1.21 # *sigh* - it appears there are no rules here at all, so when we need # to know the info, we must load the tlb by filename and request it. # The Resolve() method on the TypelibSpec does this. # For this reason, keep the version numbers as strings - that # way we can't be wrong! Let code that really needs an int to work # out what to do. FWIW, http://support.microsoft.com/kb/816970 is # pretty clear that they *should* be hex. major = major_minor[0] minor = major_minor[1] key3 = win32api.RegOpenKey(key2, str(version)) try: # The "FLAGS" are at this point flags = int(win32api.RegQueryValue(key3, "FLAGS")) except (win32api.error, ValueError): flags = 0 if flags & excludeFlags == 0: for lcid, crap in EnumKeys(key3): try: lcid = int(lcid) except ValueError: # not an LCID entry continue # Only care about "{lcid}\win32" key - jump straight there. try: key4 = win32api.RegOpenKey(key3, "%s\\win32" % (lcid,)) except win32api.error: continue try: dll, typ = win32api.RegQueryValueEx(key4, None) if typ == win32con.REG_EXPAND_SZ: dll = win32api.ExpandEnvironmentStrings(dll) except win32api.error: dll = None spec = TypelibSpec(iid, lcid, major, minor, flags) spec.dll = dll spec.desc = tlbdesc spec.ver_desc = tlbdesc + " (" + version + ")" results.append(spec) return results
def CheckRegisteredExe(exename): try: os.stat( win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exename)) # except SystemError: except (os.error, win32api.error): print("Registration of %s - Not registered correctly" % exename)
def CreateInstance(clsid, reqIID): """Create a new instance of the specified IID The COM framework **always** calls this function to create a new instance for the specified CLSID. This function looks up the registry for the name of a policy, creates the policy, and asks the policy to create the specified object by calling the _CreateInstance_ method. Exactly how the policy creates the instance is up to the policy. See the specific policy documentation for more details. """ # First see is sys.path should have something on it. try: addnPaths = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regAddnPath % clsid).split(';') for newPath in addnPaths: if newPath not in sys.path: sys.path.insert(0, newPath) except win32api.error: pass try: policy = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regPolicy % clsid) policy = resolve_func(policy) except win32api.error: policy = DefaultPolicy try: dispatcher = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regDispatcher % clsid) if dispatcher: dispatcher = resolve_func(dispatcher) except win32api.error: dispatcher = None if dispatcher: retObj = dispatcher(policy, None) else: retObj = policy(None) return retObj._CreateInstance_(clsid, reqIID)
def GetRegisteredNamedPath(name): """Get a registered named path, or None if it doesnt exist. """ keyStr = BuildDefaultPythonKey() + "\\PythonPath" if name: keyStr = keyStr + "\\" + name try: return win32api.RegQueryValue(GetRootKey(), keyStr) except win32api.error as exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise return None
def EnumKeys(root): index = 0 ret = [] while True: try: item = win32api.RegEnumKey(root, index) except win32api.error: break try: # Note this doesn't handle REG_EXPAND_SZ, but the implementation # here doesn't need to - that is handled as the data is read. val = win32api.RegQueryValue(root, item) except win32api.error: val = "" # code using this assumes a string. ret.append((item, val)) index = index + 1 return ret
def GetSubList(self): # Explicit lookup in the registry. ret = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") win32ui.DoWaitCursor(1) try: num = 0 while True: try: keyName = win32api.RegEnumKey(key, num) except win32api.error: break # Enumerate all version info subKey = win32api.RegOpenKey(key, keyName) name = None try: subNum = 0 bestVersion = 0.0 while True: try: versionStr = win32api.RegEnumKey(subKey, subNum) except win32api.error: break try: versionFlt = float(versionStr) except ValueError: versionFlt = 0 # ???? if versionFlt > bestVersion: bestVersion = versionFlt name = win32api.RegQueryValue(subKey, versionStr) subNum = subNum + 1 finally: win32api.RegCloseKey(subKey) if name is not None: ret.append( HLIRegisteredTypeLibrary((keyName, versionStr), name)) num = num + 1 finally: win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) ret.sort() return ret
def LocatePythonServiceExe(exeName=None): if not exeName and hasattr(sys, "frozen"): # If py2exe etc calls this with no exeName, default is current exe. return sys.executable # Try and find the specified EXE somewhere. If specifically registered, # use it. Otherwise look down sys.path, and the global PATH environment. if exeName is None: if os.path.splitext(win32service.__file__)[0].endswith("_d"): exeName = "PythonService_d.exe" else: exeName = "PythonService.exe" # See if it exists as specified if os.path.isfile(exeName): return win32api.GetFullPathName(exeName) baseName = os.path.splitext(os.path.basename(exeName))[0] try: exeName = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\%s\\%s" % (baseName, sys.winver)) if os.path.isfile(exeName): return exeName raise RuntimeError("The executable '%s' is registered as the Python " "service exe, but it does not exist as specified" % exeName) except win32api.error: # OK - not there - lets go a-searchin' for path in [sys.prefix] + sys.path: look = os.path.join(path, exeName) if os.path.isfile(look): return win32api.GetFullPathName(look) # Try the global Path. try: return win32api.SearchPath(None, exeName)[0] except win32api.error: msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % ( exeName, exeName) raise error(msg)
def IIDToInterfaceName(iid): """Converts an IID to a string interface name. Used primarily for debugging purposes, this allows a cryptic IID to be converted to a useful string name. This will firstly look for interfaces known (ie, registered) by pythoncom. If not known, it will look in the registry for a registered interface. iid -- An IID object. Result -- Always a string - either an interface name, or '<Unregistered interface>' """ try: return pythoncom.ServerInterfaces[iid] except KeyError: try: try: return win32api.RegQueryValue( win32con.HKEY_CLASSES_ROOT, "Interface\\%s" % iid) except win32api.error: pass except ImportError: pass return str(iid)
def CheckHelpFiles(verbose): if verbose: print("Help Files:") try: key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error as exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise return try: keyNo = 0 while True: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) if verbose: print("\t" + helpDesc + ":", end=' ') # query the os section. try: os.stat(helpFile) if verbose: print(helpFile) except os.error: print("** Help file %s does not exist" % helpFile) keyNo = keyNo + 1 except win32api.error as exc: import winerror if exc.winerror != winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key)
def GetRegisteredExe(exeAlias): """Get a registered .exe """ return win32api.RegQueryValue(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias)
def GetRegistryDefaultValue(subkey, rootkey=None): """A helper to return the default value for a key in the registry. """ if rootkey is None: rootkey = GetRootKey() return win32api.RegQueryValue(rootkey, subkey)
RegisterClasses(*classes, **flags) except win32api.error as exc: # If we are on xp+ and have "access denied", retry using # ShellExecuteEx with 'runas' verb to force elevation (vista) and/or # admin login dialog (vista/xp) if flags['unattended'] or exc.winerror != winerror.ERROR_ACCESS_DENIED \ or sys.getwindowsversion()[0] < 5: raise ReExecuteElevated(flags) def RegisterPyComCategory(): """ Register the Python COM Server component category. """ regCat = _cat_registrar() regCat.RegisterCategories([(CATID_PythonCOMServer, 0x0409, "Python COM Server")]) if not pythoncom.frozen: try: win32api.RegQueryValue( win32con.HKEY_CLASSES_ROOT, 'Component Categories\\%s' % CATID_PythonCOMServer) except win32api.error: try: RegisterPyComCategory() # Error with the COM category manager - oh well. except pythoncom.error: pass