我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用winreg.EnumKey()。
def _list_items(self): cpitems = {} try: reg_ns = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace") reg_classes = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID") panel_idx = 0 while 1: clsid = winreg.EnumKey(reg_ns, panel_idx) panel_idx += 1 try: reg_clsid = winreg.OpenKey(reg_classes, clsid) cpitem_info = self._list_item_info(clsid, reg_clsid) if cpitem_info: cpitems[cpitem_info['clsid']] = cpitem_info except OSError: pass except OSError: pass return cpitems
def enumRegKeySubkeys(self, key): """List all sub-keys of a specified key in the windows registry @param key: The registry key to check. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string """ hkey, key = self._getHiveAndKey(key) aReg = reg.ConnectRegistry(None, hkey) aKey = reg.OpenKey(aReg, key) result = [] index = 0 # The function EnumKey() retrieves the name of one subkey each time it is called. # It is typically called repeatedly, until an EnvironmentError exception # is raised, indicating no more values. while True: try: subkey = reg.EnumKey(aKey, index) result.append(subkey) index += 1 except EnvironmentError: return result
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: yield ctype i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, r'MIME\Database\Content Type') as mimedb: for ctype in enum_types(mimedb): try: with _winreg.OpenKey(mimedb, ctype) as key: suffix, datatype = _winreg.QueryValueEx(key, 'Extension') except EnvironmentError: continue if datatype != _winreg.REG_SZ: continue self.add_type(ctype, suffix, strict)
def _reg_query_sub_keys(handle, key, keylist = []): reghandle = reg.OpenKey(handle, key, 0, reg.KEY_READ) try: i = 0 while True: subkey = reg.EnumKey(reghandle, i) i += 1 _reg_query_sub_keys(handle, key + subkey + "\\", keylist) except WindowsError as ex: if ex.winerror == 259: keylist.append(key) finally: reg.CloseKey(reghandle)
def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") except WindowsError: # No registered Python installations return {} i = 0 versions = [] while True: try: versions.append(winreg.EnumKey(python_core, i)) i = i + 1 except WindowsError: break exes = dict() for ver in versions: try: path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver) except WindowsError: continue exes[ver] = join(path, "python.exe") winreg.CloseKey(python_core) # Add the major versions # Sort the keys, then repeatedly update the major version entry # Last executable (i.e., highest version) wins with this approach for ver in sorted(exes): exes[ver[0]] = exes[ver] return exes
def _enumerate_reg_keys(key): return _RegKeyDict._enumerate_reg(key, winreg.EnumKey)
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: if '\0' not in ctype: yield ctype i += 1 with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue
def next(self): try: k = _winreg.EnumKey(self.key.hkey,self.index) except WindowsError: raise StopIteration else: self.index += 1 return Key(k,self.key)
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: yield ctype i += 1 with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue
def walk_registry(hkey, path, access_flags, keywords, onerror=None): """ Walks all keys of the registry searching for values that match any of the provided 'keywords'. """ try: key = winreg.OpenKey(hkey, path, access_flags) except OSError as e: if onerror is not None: onerror(e) return i = 0 sub_keys = [] with key: while True: try: sub_keys.append(winreg.EnumKey(key, i)) except OSError: break i += 1 i = 0 while True: try: data = winreg.EnumValue(key, i) i += 1 for keyword in keywords: if keyword.lower() in str(data[0]).lower(): if hkey == winreg.HKEY_LOCAL_MACHINE: hive = 'HKLM\\' else: hive = 'HKCU\\' print('{0}\\{1}\\{2} = {3}'.format(hive, path, data[0], data[1])) except OSError: break for key in sub_keys: next_path = os.path.join(path, key) for item in walk_registry(hkey, next_path, access_flags, keywords, onerror): yield item
def get_localzone_name(): # Windows is special. It has unique time zone names (in several # meanings of the word) available, but unfortunately, they can be # translated to the language of the operating system, so we need to # do a backwards lookup, by going through all time zones and see which # one matches. handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' localtz = winreg.OpenKey(handle, TZLOCALKEYNAME) keyvalues = valuestodict(localtz) localtz.Close() if 'TimeZoneKeyName' in keyvalues: # Windows 7 (and Vista?) # For some reason this returns a string with loads of NUL bytes at # least on some systems. I don't know if this is a bug somewhere, I # just work around it. tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0] else: # Windows 2000 or XP # This is the localized name: tzwin = keyvalues['StandardName'] # Open the list of timezones to look up the real name: TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' tzkey = winreg.OpenKey(handle, TZKEYNAME) # Now, match this value to Time Zone information tzkeyname = None for i in range(winreg.QueryInfoKey(tzkey)[0]): subkey = winreg.EnumKey(tzkey, i) sub = winreg.OpenKey(tzkey, subkey) data = valuestodict(sub) sub.Close() if data['Std'] == tzwin: tzkeyname = subkey break tzkey.Close() handle.Close() if tzkeyname is None: raise LookupError('Can not find Windows timezone configuration') timezone = tz_names.get(tzkeyname) if timezone is None: # Nope, that didn't work. Try adding 'Standard Time', # it seems to work a lot of times: timezone = tz_names.get(tzkeyname + ' Standard Time') # Return what we have. if timezone is None: raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname) return timezone
def read_registry(self): """Extract resolver configuration from the Windows registry.""" lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) want_scan = False try: try: # XP, 2000 tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters') want_scan = True except EnvironmentError: # ME tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\VxD\MSTCP') try: self._config_win32_fromkey(tcp_params) finally: tcp_params.Close() if want_scan: interfaces = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters' r'\Interfaces') try: i = 0 while True: try: guid = _winreg.EnumKey(interfaces, i) i += 1 key = _winreg.OpenKey(interfaces, guid) if not self._win32_is_nic_enabled(lm, guid, key): continue try: self._config_win32_fromkey(key) finally: key.Close() except EnvironmentError: break finally: interfaces.Close() finally: lm.Close()
def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! if sys.version_info[0] >= 3: import winreg else: import _winreg as winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)"\ "\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print(sys.exc_info()[1], '(ignoring)') self.__class__.info = info
def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! if sys.version_info[0] >= 3: import winreg else: import _winreg as winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" r"\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print(sys.exc_info()[1], '(ignoring)') self.__class__.info = info
def _detect_distro_official(self, given_enabled, given_label, given_path): dist_props = { 'enabled': given_enabled, 'label': given_label, 'exe_file': None, 'cmd_args': ['-load', '%1'], 'sessions': []} # label if not dist_props['label']: dist_props['label'] = "PuTTY" # enabled? don't go further if not if dist_props['enabled'] is None: dist_props['enabled'] = True if not dist_props['enabled']: return dist_props # find executable exe_file = None if given_path: exe_file = os.path.normpath(os.path.join(given_path, self.EXE_NAME_OFFICIAL)) if not os.path.exists(exe_file): exe_file = None if not exe_file: exe_file = self._autodetect_official_installreg() if not exe_file: exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "PuTTY.lnk") if not exe_file: exe_file = self._autodetect_official_progfiles() if not exe_file: exe_file = self._autodetect_path(self.EXE_NAME_OFFICIAL) #if not exe_file: # exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "*putty*.lnk") if not exe_file: return None dist_props['exe_file'] = exe_file # list configured sessions try: hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, 'Software\\SimonTatham\\PuTTY\\Sessions') index = 0 while True: try: dist_props['sessions'].append(urllib.parse.unquote( winreg.EnumKey(hkey, index), encoding='mbcs')) index += 1 except OSError: break winreg.CloseKey(hkey) except OSError: pass return dist_props