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 FindPythonExe(exeAlias, possibleRealNames, searchPaths): """Find an exe. Returns the full path to the .exe, and a boolean indicating if the current registered entry is OK. We don't trust the already registered version even if it exists - it may be wrong (ie, for a different Python version) """ import win32api, regutil, string, os, sys if possibleRealNames is None: possibleRealNames = exeAlias # Look first in Python's home. found = os.path.join(sys.prefix, possibleRealNames) if not FileExists(found): # for developers found = os.path.join(sys.prefix, "PCBuild", possibleRealNames) if not FileExists(found): found = LocateFileName(possibleRealNames, searchPaths) registered_ok = 0 try: registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias) registered_ok = found==registered except win32api.error: pass return found, registered_ok
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)
UnregisterClasses(*classes, **flags) else: 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() except pythoncom.error: # Error with the COM category manager - oh well. pass
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 1: try: appName = win32api.RegEnumKey(key, keyNo) appPath = win32api.RegQueryValue(key, appName) if verbose: print "\t" + appName + ":", 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)
""" monitor_dir = r'path:/to/recordings' # Get the Explorer overlay ID that's used to show synced status in Google Backup and Sync. # TODO: Save to disk or set env var instead of running every time. reg_key = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers', ) i = 0 try: while True: overlay_name = win32api.RegEnumKey(reg_key, i) if overlay_name == 'GoogleDriveSynced': overlay_handler_ID = win32api.RegQueryValue(reg_key, overlay_name) break; i += 1 except win32api.error as e: if e.winerror == 259: # Couldn't find Google Backup and Drive handler, try hardcoded one anyway overlay_handler_ID = '{81539FE6-33C7-4CE7-90C7-1C7B8F2F2D40}' finally: win32api.RegCloseKey(reg_key) try: ovh = pythoncom.CoCreateInstance(overlay_handler_ID, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellIconOverlayIdentifier) except com_error as e:
win32api.RegQueryValueEx(key,valueName) # 读取某一项值;其参数含义如下: Key:已经打开的注册表项的句柄。 valueName:要读取的项值名称。 win32api.RegQueryInfoKey(key) # RegQueryInfoKey函数查询项的基本信息; 返回项的子项数目、项值数目,以及最后一次修改时间 如: import win32api import win32con # 打开“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer”项 key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,'SOFTWARE\\Microsoft\\Internet Explorer',0, win32con.KEY_ALL_ACCESS) # 读取项的默认值'' # 输出为空,表示其默认值未设置 print win32api.RegQueryValue(key,'') #读取项值名称为Version的项值数据,也就是Internet Explorer的版本 print win32api.RegQueryValueEx(key,'Version') # 显示如:('6.0.2900.2180', 1) print win32api.RegQueryInfoKey(key) # 查询项的基本信息,显示如:(26, 7, 128178812229687500L) 6. 设置项值 win32api.RegSetValue(key,subKey,type,value) # 设置项的默认值 Key:已经打开的项的句柄。 subKey:所要设置的子项。 Type:项值的类型,必须为 win32con.REG_SZ。 Value:项值数据,为字符串。 win32api.RegSetValueEx(key,valueName,reserved,type,value) # 要修改或重新设置注册表某一项的项值。如果项值存在,则修改该项值,如果不存在,则添加该项值。 Key:要设置的项的句柄。 valueName:要设置的项值名称。
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 EnumTypeLib(): ret = [] libKeys = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 while 1: try: keyName = win32api.RegEnumKey(key, num) #print keyName except win32api.error: break # Enumerate all version info subKey = win32api.RegOpenKey(key, keyName) name = None try: subNum = 0 bestVersion = 0.0 while 1: 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: libKeys.append((keyName, versionStr)) #print name num += 1 except: pass for keyName, versionStr in libKeys: key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (keyName, versionStr)) num = 0 while True: try: subKey = win32api.RegEnumKey(key, num) #print subKey except: break hSubKey = win32api.RegOpenKey(key, subKey) try: value, typ = win32api.RegQueryValueEx(hSubKey, None) if typ == win32con.REG_EXPAND_SZ: value = win32api.ExpandEnvironmentStrings(value) except: value = "" if subKey=="HELPDIR": helpPath = value elif subKey.lower()=="flags": flags = value else: try: lcid = int(subKey) #print key #print key, subKey lcidkey = win32api.RegOpenKey(key, subKey) #print lcidkey # Enumerate the platforms lcidnum = 0 while 1: try: platform = win32api.RegEnumKey(lcidkey, lcidnum) #print platform except Exception, e: #print 111,e break try: hplatform = win32api.RegOpenKey(lcidkey, platform) fname, typ = win32api.RegQueryValueEx(hplatform, None) if fname != None: ret.append((fname, keyName)) #print key2 #print fname #print lcid, platform, fname #if typ == win32con.REG_EXPAND_SZ: #fname = win32api.ExpandEnvironmentStrings(fname) #print fname except win32api.error: fname = "" #collected.append((lcid, platform, fname)) lcidnum = lcidnum + 1 win32api.RegCloseKey(lcidkey) except ValueError,e: #print e pass num += 1
def SetupEnvironment(): HKEY_LOCAL_MACHINE = -2147483646 # Avoid pulling in win32con for just these... KEY_QUERY_VALUE = 0x1 # Open the root key once, as this is quite slow on NT. keyName = "SOFTWARE\\Python\\PythonCore\\%s\\PythonPath\\win32com" % sys.winver try: key = win32api.RegOpenKey(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE) except win32api.error: key = None try: found = 0 if key is not None: try: __path__.append(win32api.RegQueryValue(key, "Extensions")) found = 1 except win32api.error: # Nothing registered pass if not found: try: __path__.append( win32api.GetFullPathName(__path__[0] + "\\..\\win32comext")) except win32api.error: # Give up in disgust! pass # For the sake of developers, we also look up a "BuildPath" key # If extension modules add support, we can load their .pyd's from a completely # different directory (see the comments below) try: if key is not None: global __build_path__ __build_path__ = win32api.RegQueryValue(key, "BuildPath") __path__.append(__build_path__) except win32api.error: # __build_path__ neednt be defined. pass found = 0 global __gen_path__ try: if key is not None: __gen_path__ = win32api.RegQueryValue(key, "GenPath") found = 1 # Import a special module, Otherwise it is already all setup for us. import new global gen_py # Exists in the win32com namespace. gen_py = new.module("win32com.gen_py") gen_py.__path__ = [__gen_path__] sys.modules[gen_py.__name__] = gen_py except win32api.error: found = 0 if not found: __gen_path__ = win32api.GetFullPathName(__path__[0] + "\\gen_py") finally: if key is not None: key.Close()
import os import sys import string import win32api, win32con from win32con import * # For now: #progdir=os.path.split(sys.argv[0])[0] #CMIFDIR=os.path.split(progdir)[0] import win32ui h1 = win32ui.GetMainFrame() #h1.ShowWindow(win32con.SW_HIDE) #CMIFDIR = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\CmifPath") CMIFDIR = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "Software\\Chameleon\\CmifPath") CMIFPATH = [ os.path.join(CMIFDIR, 'editor\\win32'), os.path.join(CMIFDIR, 'editor'), os.path.join(CMIFDIR, 'common\\win32'), os.path.join(CMIFDIR, 'common'), os.path.join(CMIFDIR, 'lib\\win32'), os.path.join(CMIFDIR, 'lib'), os.path.join(CMIFDIR, 'pylib'), os.path.join(CMIFDIR, 'pylib\\audio'), ] CMIF_USE_WIN32 = "ON" #CHANNELDEBUG="ON" # create blank html file dir1 = CMIFDIR + '\\tmp.htm'
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 # Check for both "{lcid}\win32" and "{lcid}\win64" keys. try: key4 = win32api.RegOpenKey(key3, "%s\\win32" % (lcid, )) except win32api.error: try: key4 = win32api.RegOpenKey(key3, "%s\\win64" % (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 GetDefaultVerb(szExt, szCmdLine): szVerb = '' #print 'GetDefaultVerb' #return #//File extension string equals to the registry key name. #//Value of this key points to another registry key describing shell actions #//for given file format (described by file extension string) szKey = '' if FindExecutableKey(szExt, szKey): #//TOFIX lstrcpyn szKey2 = szKey szKey2 += '\\shell' #//See if 'shell' subkey has default value defined #//(default shell action verb for this format) szVerb = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, szKey2) if (GetRegKey(HKEY_CLASSES_ROOT, szKey2, szVerb) == ERROR_SUCCESS) and len(szVerb) > 0: #//test if the verb is valid (must have valid 'command' subkey) szKey2 += '\\' szKey2 += szVerb szKey2 += '\\command' #//default value of '\\shell\\VERB\\command' subkey (replace VERB with actual value) #//gives us command line string (app + parameters) if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: return True szCmdLine = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, szKey2) if len(szCmdLine) > 0: return szVerb, True #//no default verb defined else: #//test for presence of standard 'open' subkey #//TOFIX lstrcpyn szKey2 = szKey #print szKey2 #szKey2 += '\\shell\\open\\command' szKey2 += '\\shell\\shell\\open\\command' # auf meinem pc francesco #print szKey2 #TODO szCmdLine = '' #szCmdLine = win32api.RegQueryValue (win32con.HKEY_CLASSES_ROOT, szKey2) if len(szCmdLine) > 0: szVerb = 'open' #TODO: it works? if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: szVerb = _('open') return szVerb, True #//else (last chance to find default verb) #//take first available subkey under 'shell' #//TOFIX lstrcpyn szKey2 = szKey szKey2 += '\\shell' #//enumerate subkeys until we find first subkey name #HKEY hkey; #RegOpenKeyEx(key, subKey , reserved , sam ) try: win32api.RegOpenKeyEx(win32con.HKEY_CLASSES_ROOT, szKey2, 0, KEY_ENUMERATE_SUB_KEYS) #LONG retval = RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey2, 0, KEY_ENUMERATE_SUB_KEYS, &hkey); ##retval = 0, #TODO: returns tuple? retval = win32api.RegEnumKeyEx(hkey) #retval = RegEnumKeyEx(hkey, 0, szVerb, &datasize, NULL, NULL, NULL, NULL); #RegCloseKey(hkey); win32api.RegCloseKey(hkey) #if (retval == ERROR_SUCCESS): if (retval != 0): #//test if the verb is valid (must have valid 'command' subkey) szKey2 = '\\' szKey2 += szVerb szKey2 += '\\command' #//default value of '\\shell\\VERB\\command' subkey (replace VERB with actual value) #//gives us command line string (app + parameters) #TODO: it works? if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: return True szCmdLine = win32api.RegQueryValue( win32con.HKEY_CLASSES_ROOT, szKey2) return szVerb, True except: pass return szVerb, False
def _get_registered_typelibs(match='HEC River Analysis System'): """ adapted from pywin32 # Copyright (c) 1996-2008, Greg Stein and Mark Hammond. """ import win32api import win32con # Explicit lookup in the registry. result = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 while 1: try: key_name = win32api.RegEnumKey(key, num) except win32api.error: break # Enumerate all version info sub_key = win32api.RegOpenKey(key, key_name) name = None try: sub_num = 0 best_version = 0.0 while 1: try: version_str = win32api.RegEnumKey(sub_key, sub_num) except win32api.error: break try: version_flt = float(version_str) except ValueError: version_flt = 0 # ???? if version_flt > best_version: best_version = version_flt name = win32api.RegQueryValue(sub_key, version_str) sub_num = sub_num + 1 finally: win32api.RegCloseKey(sub_key) if name is not None and match in name: fname, lcid = _get_typelib_info(key_name, version_str) # Split version major, minor = version_str.split('.') result.append({'name': name, 'filename': fname, 'iid': key_name, 'lcid': lcid, 'major': int(major), 'minor': int(minor)}) num = num + 1 finally: win32api.RegCloseKey(key) #print(result) #result = sorted(result) return result
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)
def GetRegisteredExe(exeAlias): """Get a registered .exe """ return win32api.RegQueryValue(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias)
retList = [] try: key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error, exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = keyNo + 1 except win32api.error, exc: import winerror if exc.winerror != winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key) return retList def SelectAndRunHelpFile(): from pywin.dialogs import list helpFiles = ListAllHelpFiles()