我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32api.RegQueryValueEx()。
def testValues(self): key_name = r'PythonTestHarness\win32api' ## tuples containing value name, value type, data values=( (None, win32con.REG_SZ, 'This is default unnamed value'), ('REG_SZ', win32con.REG_SZ,'REG_SZ text data'), ('REG_EXPAND_SZ', win32con.REG_EXPAND_SZ, '%systemdir%'), ## REG_MULTI_SZ value needs to be a list since strings are returned as a list ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']), ('REG_MULTI_SZ_empty', win32con.REG_MULTI_SZ, []), ('REG_DWORD', win32con.REG_DWORD, 666), ('REG_QWORD', win32con.REG_QWORD, 2**33), ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')), ) hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name) for value_name, reg_type, data in values: win32api.RegSetValueEx(hkey, value_name, None, reg_type, data) for value_name, orig_type, orig_data in values: data, typ=win32api.RegQueryValueEx(hkey, value_name) self.assertEqual(typ, orig_type) self.assertEqual(data, orig_data)
def _win32_getvalue(key,name,default=''): """ Read a value for name from the registry key. In case this fails, default is returned. """ try: # Use win32api if available from win32api import RegQueryValueEx except ImportError: # On Python 2.0 and later, emulate using _winreg import _winreg RegQueryValueEx = _winreg.QueryValueEx try: return RegQueryValueEx(key,name) except: return default
def _GetServiceShortName(longName): # looks up a services name # from the display name # Thanks to Andy McKay for this code. access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access) num = win32api.RegQueryInfoKey(hkey)[0] longName = longName.lower() # loop through number of subkeys for x in range(0, num): # find service name, open subkey svc = win32api.RegEnumKey(hkey, x) skey = win32api.RegOpenKey(hkey, svc, 0, access) try: # find display name thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0]) if thisName.lower() == longName: return svc except win32api.error: # in case there is no key called DisplayName pass return None # Open a service given either it's long or short name.
def GetDefaultProfileName(): import win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles") try: return win32api.RegQueryValueEx(key, "DefaultProfile")[0] finally: key.Close() except win32api.error: return None # # Recursive dump of folders. #
def _win32_getvalue(key,name,default=''): """ Read a value for name from the registry key. In case this fails, default is returned. """ try: # Use win32api if available from win32api import RegQueryValueEx except ImportError: # On Python 2.0 and later, emulate using winreg import winreg RegQueryValueEx = winreg.QueryValueEx try: return RegQueryValueEx(key,name) except: return default
def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK import os, win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: path = win32api.RegQueryValueEx(key, helpDesc)[0] if FileExists(os.path.join(path, helpFile)): return os.path.abspath(path) except win32api.error: pass # no registry entry. finally: key.Close() except win32api.error: pass for pathLook in searchPaths: if FileExists(os.path.join(pathLook, helpFile)): return os.path.abspath(pathLook) pathLook = os.path.join(pathLook, "Help") if FileExists(os.path.join( pathLook, helpFile)): return os.path.abspath(pathLook) raise error("The help file %s can not be located" % helpFile)
def __FindSvcDeps(findName): if type(findName) is pywintypes.UnicodeType: findName = str(findName) dict = {} k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services") num = 0 while 1: try: svc = win32api.RegEnumKey(k, num) except win32api.error: break num = num + 1 sk = win32api.RegOpenKey(k, svc) try: deps, typ = win32api.RegQueryValueEx(sk, "DependOnService") except win32api.error: deps = () for dep in deps: dep = dep.lower() dep_on = dict.get(dep, []) dep_on.append(svc) dict[dep]=dep_on return __ResolveDeps(findName, dict)
def get_user_paths(): try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_USERS, None , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return 0 paths = [] subkeys = win32api.RegEnumKeyEx(keyh) for subkey in subkeys: try: subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] + "\\Environment" , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: pass else: subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh) try: path, type = win32api.RegQueryValueEx(subkeyh, "PATH") paths.append((subkey[0], path)) except: pass return paths
def get_system_path(): # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment key_string = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, key_string , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return None try: path, type = win32api.RegQueryValueEx(keyh, "PATH") return path except: return None #name=sys.argv[1] #if not os.path.exists(name): #print name, "does not exist!" #sys.exit()
def _win32_getvalue(key, name, default=''): """ Read a value for name from the registry key. In case this fails, default is returned. """ try: # Use win32api if available from win32api import RegQueryValueEx except ImportError: # On Python 2.0 and later, emulate using winreg import winreg RegQueryValueEx = winreg.QueryValueEx try: return RegQueryValueEx(key, name) except: return default
def getProgramsMenuPath(): """Get the path to the Programs menu. Probably will break on non-US Windows. @returns: the filesystem location of the common Start Menu->Programs. """ if not platform.isWinNT(): return "C:\\Windows\\Start Menu\\Programs" keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders' hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyname, 0, win32con.KEY_READ) return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def getProgramFilesPath(): """Get the path to the Program Files folder.""" keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyname, 0, win32con.KEY_READ) return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or u'' # Don't want "None" ever being returned.
def find_pdh_counter_localized_name(english_name, machine_name = None): if not counter_english_map: import win32api, win32con counter_reg_value = win32api.RegQueryValueEx(win32con.HKEY_PERFORMANCE_DATA, "Counter 009") counter_list = counter_reg_value[0] for i in xrange(0, len(counter_list) - 1, 2): try: counter_id = int(counter_list[i]) except ValueError: continue counter_english_map[counter_list[i+1].lower()] = counter_id return win32pdh.LookupPerfNameByIndex(machine_name, counter_english_map[english_name.lower()])
def LocateSpecificServiceExe(serviceName): # Given the name of a specific service, return the .EXE name _it_ uses # (which may or may not be the Python Service EXE hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS) try: return win32api.RegQueryValueEx(hkey, "ImagePath")[0] finally: hkey.Close()
def GetServiceCustomOption(serviceName, option, defaultValue = None): # First param may also be a service class/instance. # This allows services to pass "self" try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: try: return win32api.RegQueryValueEx(key, option)[0] except win32api.error: # No value. return defaultValue finally: win32api.RegCloseKey(key)
def getRegistryParameters(servicename): key=win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"+servicename) try: try: (commandLine, regtype) = win32api.RegQueryValueEx(key,pyroArgsRegkeyName) return commandLine except: pass finally: key.Close() createRegistryParameters(servicename, pyroArgsRegkeyName) return ""
def RegGetValue(root, key): """This utility function returns a value in the registry without having to open the key first. Only available on Windows platforms with a version of Python that can read the registry. Returns the same thing as SCons.Util.RegQueryValueEx, except you just specify the entire path to the value, and don't have to bother opening the key first. So: Instead of: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion') out = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') You can write: out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir') """ # I would use os.path.split here, but it's not a filesystem # path... p = key.rfind('\\') + 1 keyp = key[:p-1] # -1 to omit trailing slash val = key[p:] k = RegOpenKeyEx(root, keyp) return RegQueryValueEx(k,val)
def _GetRegistryValue(key, val, default = None): # val is registry value - None for default val. try: hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: try: hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: return default
def GetItemsCurrentValue(self, item, valueName): hkey = win32api.RegOpenKey(item.keyRoot, item.keyName) try: val, type = win32api.RegQueryValueEx(hkey, valueName) if type != win32con.REG_SZ: raise TypeError("Only strings can be edited") return val finally: win32api.RegCloseKey(hkey)
def check_masterPassword(self): accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Configuration\Security', 0, accessRead) thisName = str(win32api.RegQueryValueEx(key, 'UseMasterPassword')[0]) if thisName == '0': return False else: return True
def get_default_database(self): accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\ACS\\PuTTY Connection Manager', 0, accessRead) thisName = str(win32api.RegQueryValueEx(key, 'DefaultDatabase')[0]) if thisName: return thisName else: return ' '
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or '' # Don't want "None" ever being returned.
def find_pdh_counter_localized_name(english_name, machine_name = None): if not counter_english_map: import win32api, win32con counter_reg_value = win32api.RegQueryValueEx(win32con.HKEY_PERFORMANCE_DATA, "Counter 009") counter_list = counter_reg_value[0] for i in range(0, len(counter_list) - 1, 2): try: counter_id = int(counter_list[i]) except ValueError: continue counter_english_map[counter_list[i+1].lower()] = counter_id return win32pdh.LookupPerfNameByIndex(machine_name, counter_english_map[english_name.lower()])
def getProgramsMenuPath(): """ Get the path to the Programs menu. Probably will break on non-US Windows. @return: the filesystem location of the common Start Menu->Programs. @rtype: L{str} """ if not platform.isWindows(): return "C:\\Windows\\Start Menu\\Programs" keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders' hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyname, 0, win32con.KEY_READ) return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def get_dbg_eng_dir_from_registry(): import win32api, win32con try: hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\DebuggingTools") except: # Lets try a few common places before failing. pgPaths = [ "c:\\", os.environ["SystemDrive"]+"\\", os.environ["ProgramFiles"], ] if "ProgramW6432" in os.environ: pgPaths.append(os.environ["ProgramW6432"]) if "ProgramFiles(x86)" in os.environ: pgPaths.append(os.environ["ProgramFiles(x86)"]) dbgPaths = [ "Debuggers", "Debugger", "Debugging Tools for Windows", "Debugging Tools for Windows (x64)", "Debugging Tools for Windows (x86)", ] for p in pgPaths: for d in dbgPaths: testPath = os.path.join(p,d) if os.path.exists(testPath): return testPath raise DebuggerException("Failed to locate Microsoft Debugging Tools in the registry. Please make sure its installed") val, type = win32api.RegQueryValueEx(hkey, "WinDbg") return val