我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用winreg.HKEY_LOCAL_MACHINE。
def register(classobj): import winreg subKeyCLSID = "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s" % classobj._reg_clsid_ try: hKey = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, subKeyCLSID ) subKey = winreg.SetValueEx( hKey, "ButtonText", 0, winreg.REG_SZ, classobj._button_text_ ) winreg.SetValueEx( hKey, "ClsidExtension", 0, winreg.REG_SZ, classobj._reg_clsid_ ) # reg value for calling COM object winreg.SetValueEx( hKey, "CLSID", 0, winreg.REG_SZ, "{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}" ) # CLSID for button that sends command to COM object winreg.SetValueEx( hKey, "Default Visible", 0, winreg.REG_SZ, "Yes" ) winreg.SetValueEx( hKey, "ToolTip", 0, winreg.REG_SZ, classobj._tool_tip_ ) winreg.SetValueEx( hKey, "Icon", 0, winreg.REG_SZ, classobj._icon_) winreg.SetValueEx( hKey, "HotIcon", 0, winreg.REG_SZ, classobj._hot_icon_) except WindowsError: print("Couldn't set standard toolbar reg keys.") else: print("Set standard toolbar reg keys.")
def __init__(self, **kwargs): python_version = kwargs.pop('python', '3.4') python_path = None for node in ('Wow6432Node\\', ''): try: key = compat_winreg.OpenKey( compat_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\%sPython\PythonCore\%s\InstallPath' % (node, python_version)) try: python_path, _ = compat_winreg.QueryValueEx(key, '') finally: compat_winreg.CloseKey(key) break except Exception: pass if not python_path: raise BuildError('No such Python version: %s' % python_version) self.pythonPath = python_path super(PythonBuilder, self).__init__(**kwargs)
def unregister(classobj): import winreg subKeyCLSID = "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s" % classobj._reg_clsid_ try: hKey = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, subKeyCLSID ) subKey = winreg.DeleteValue( hKey, "ButtonText" ) winreg.DeleteValue( hKey, "ClsidExtension" ) # for calling COM object winreg.DeleteValue( hKey, "CLSID" ) winreg.DeleteValue( hKey, "Default Visible" ) winreg.DeleteValue( hKey, "ToolTip" ) winreg.DeleteValue( hKey, "Icon" ) winreg.DeleteValue( hKey, "HotIcon" ) winreg.DeleteKey( winreg.HKEY_LOCAL_MACHINE, subKeyCLSID ) except WindowsError: print("Couldn't delete Standard toolbar regkey.") else: print("Deleted Standard toolbar regkey.") # # test implementation #
def _find_msvc_in_registry(env,version): if _is_py2: import _winreg as winreg else: import winreg vs_ver = str(version) + '.0' vs_key = 'SOFTWARE\\Microsoft\\VisualStudio\\' + vs_ver + '\\Setup\\VS' vc_key = 'SOFTWARE\\Microsoft\\VisualStudio\\' + vs_ver + '\\Setup\\VC' vs_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vs_key, 'ProductDir') vc_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vc_key, 'ProductDir') # On a 64-bit host, look for a 32-bit installation if (not vs_dir or not vc_dir): vs_key = 'SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\' + \ vs_ver + '\\Setup\\VS' vc_key = 'SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\' + \ vs_ver + '\\Setup\\VC' vs_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vs_key, 'ProductDir') vc_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vc_key, 'ProductDir') return (vs_dir,vc_dir)
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 isVistaUACEnabled(self): """ Return boolean indicating whether this is a Windows Vista system with User Account Control enabled. Warning: If modifies the UAC setting but has not yet rebooted, this method will return the wrong result. """ if self._isVistaUACEnabled is not None: return self._isVistaUACEnabled if self.getWindowsVersion() != self.VERSION_VISTA: return False hkey = reg.HKEY_LOCAL_MACHINE key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System' value = 'EnableLUA' if not self.registryHasValue(hkey, key, value): self._isVistaUACEnabled = False elif self.getValueFromRegKey(hkey, key, value) == 0: self._isVistaUACEnabled = False else: self._isVistaUACEnabled = True return self._isVistaUACEnabled
def enumRegKeyValues(self, key): """List all values 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 @return: An array of tupples containing the name of each value, the data of the value and it's type @rtype: tupple(string, WinRegValueType) """ hkey, key = self._getHiveAndKey(key) aReg = reg.ConnectRegistry(None, hkey) aKey = reg.OpenKey(aReg, key) result = [] index = 0 # The function EnumValue() 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: valueName, valueData, valueType = reg.EnumValue(aKey, index) result.append((valueName, valueData, WinRegValueType.findByIntegerValue(valueType))) index += 1 except EnvironmentError: return result
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 setValueFromRegKey(self, key, valueName, valueData, valueType): """Sets a value in a key @param key: The registry key that holds the value to set. If the key does not exist, it will be created. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string @param valueName: The name of the value to set @type valueName: string @param valueData: The data to assign to the value @type valueData: string @param valueType: The type of the value @type valueType: WinRegValueType """ hkey, key = self._getHiveAndKey(key) aReg = reg.ConnectRegistry(None, hkey) aKey = reg.CreateKey(aReg, key) reg.SetValueEx(aKey, valueName, 0, valueType.type, valueData)
def _create_win(self): try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts') except EnvironmentError: try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') except EnvironmentError: raise FontNotFound('Can\'t open Windows font registry key') try: path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True) self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size) for style in ('ITALIC', 'BOLD', 'BOLDITALIC'): path = self._lookup_win(key, self.font_name, STYLES[style]) if path: self.fonts[style] = ImageFont.truetype(path, self.font_size) else: if style == 'BOLDITALIC': self.fonts[style] = self.fonts['BOLD'] else: self.fonts[style] = self.fonts['NORMAL'] finally: _winreg.CloseKey(key)
def _find_exe_in_registry(self): try: from _winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER import shlex keys = ( r"SOFTWARE\Classes\FirefoxHTML\shell\open\command", r"SOFTWARE\Classes\Applications\firefox.exe\shell\open\command" ) command = "" for path in keys: try: key = OpenKey(HKEY_LOCAL_MACHINE, path) command = QueryValue(key, "") break except OSError: try: key = OpenKey(HKEY_CURRENT_USER, path) command = QueryValue(key, "") break except OSError: pass else: return "" if not command: return "" return shlex.split(command)[0]
def __init__(self, scope): self.scope = scope if scope == 'user': self.root = winreg.HKEY_CURRENT_USER self.subkey = 'Environment' else: self.root = winreg.HKEY_LOCAL_MACHINE self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
def _find_devenv_path(vs_version): devenv_path = None # First try the registry, because the environment variable is unreliable # (case of Visual Studio installed on a different drive; it still sets # the envvar to point to C:\Program Files even if devenv.com is on D:\) #pylint: disable=import-error from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE key_path = 'SOFTWARE\\Classes\\VisualStudio.accessor.' + vs_version + '.0\\shell\\Open' try: with OpenKey(HKEY_LOCAL_MACHINE, key_path) as key: cmdline = QueryValue(key, 'Command') if cmdline[:1] == '"': cmdline = cmdline.split('"')[1] elif ' ' in cmdline: cmdline = cmdline.split(' ')[0] devenv_path = cmdline.replace('devenv.exe', 'devenv.com') #pylint: disable=broad-except except Exception: pass # If the registry key is unhelpful, try the environment variable if not devenv_path: vstools_path = os.getenv('VS' + vs_version + '0COMNTOOLS') if vstools_path is not None: # Sanitize this because os.path.join sometimes gets confused if vstools_path[-1] in [ '/', '\\' ]: vstools_path = vstools_path[:-1] devenv_path = os.path.join(vstools_path, '../../Common7/IDE/devenv.com') if not devenv_path or not os.path.exists(devenv_path): return None logging.info("Found Visual Studio at %s", devenv_path) return devenv_path
def _find_exe_in_registry(self): try: from _winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER import shlex keys = (r"SOFTWARE\Classes\FirefoxHTML\shell\open\command", r"SOFTWARE\Classes\Applications\firefox.exe\shell\open\command") command = "" for path in keys: try: key = OpenKey(HKEY_LOCAL_MACHINE, path) command = QueryValue(key, "") break except OSError: try: key = OpenKey(HKEY_CURRENT_USER, path) command = QueryValue(key, "") break except OSError: pass else: return "" if not command: return "" return shlex.split(command)[0]
def get_previous_install_prefixes(pyversion, arch, allusers=True): """Returns a list of prefixes for all old installations of this arch so that they can be removed from PATH if present. Note, it would be preferable to uninstall them properly instead. """ if allusers: # All Users key, subkey = (reg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\') else: # Just Me key, subkey = (reg.HKEY_CURRENT_USER, r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\') keylist = [] # We ignore pyversion and instead look for any *conda installations. regex = re.compile('Python \S+ \(\S+conda[0-9]+ \S+ '+arch+'\)') _reg_query_sub_keys(key, subkey, keylist) results = [] for uninstsubkey in keylist: final_part = os.path.basename(uninstsubkey.rstrip('\\')) if regex.match(final_part): try: with reg.OpenKeyEx(key, uninstsubkey, 0, reg.KEY_QUERY_VALUE) as keyhandle: reg_value = reg.QueryValueEx(keyhandle, 'UninstallString') results.append(os.path.dirname(re.sub(r'^"|"$', '', reg_value[0]))) except: pass return results
def read_registry(key, valueex): reg_key = OpenKey(HKEY_LOCAL_MACHINE, key, 0, KEY_READ) return QueryValueEx(reg_key, valueex)
def _FindTimeZoneKey(self): """Find the registry key for the time zone name (self.timeZoneName).""" # for multi-language compatability, match the time zone name in the # "Std" key of the time zone key. zoneNames = dict(self._get_indexed_time_zone_keys('Std')) # Also match the time zone key name itself, to be compatible with # English-based hard-coded time zones. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName) key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey) try: result = key.subkey(timeZoneName) except: raise ValueError('Timezone Name %s not found.' % timeZoneName) return result
def _get_time_zone_key(subkey=None): "Return the registry key that stores time zone details" key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey) if subkey: key = key.subkey(subkey) return key
def DllRegisterServer(): comclass = IEToolbar # register toolbar with IE try: print("Trying to register Toolbar.\n") hkey = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar" ) subKey = winreg.SetValueEx( hkey, comclass._reg_clsid_, 0, winreg.REG_BINARY, "\0" ) except WindowsError: print("Couldn't set registry value.\nhkey: %d\tCLSID: %s\n" % ( hkey, comclass._reg_clsid_ )) else: print("Set registry value.\nhkey: %d\tCLSID: %s\n" % ( hkey, comclass._reg_clsid_ )) # TODO: implement reg settings for standard toolbar button # unregister plugin
def MimeToMapi (self, eml, m, flag = 0) : if self.converter == None : clsid = win32com.mapi.mapi.CLSID_IConverterSession iid = win32com.mapi.mapi.IID_IConverterSession try: tmp = pythoncom.CoCreateInstance (clsid, None, pythoncom.CLSCTX_INPROC_SERVER, pythoncom.IID_IUnknown) self.converter = tmp.QueryInterface (iid) except : # Test for ClickToRun version of Outlook and manually load library and create instance for iconvpath in ("", "16.0", "15.0") : regpath = os.path.join ("Software","Microsoft","Office",iconvpath,"ClickToRun","Registry","Machine","Software","Classes") if platform.machine() == "AMD64" and platform.architecture()[0] == "32bit": # 32bit application on 64bit platform regpath = os.path.join (regpath,"Wow6432Node") regpath = os.path.join (regpath,"CLSID", str(clsid),"InprocServer32") self.converter = self.CoCreateInstanceC2R (winreg.HKEY_LOCAL_MACHINE, regpath, clsid, iid) if self.converter != None : break if self.converter == None : NameError("mapi:MimeToMapi : Can not create IConverterSession instance") # Open file as IStream. Don't use win32com.mapi.mapi.OpenStreamOnFile as it doesn't # handle Unicode file names f = open(eml, "rb") Istrm = util.wrap (FileStream(f), pythoncom.IID_IUnknown, None, True) self.converter.MIMEToMAPI(Istrm, m, flag)
def OutlookPath(): """Function to retrieve the path to Outlook from the registry""" aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) aKey = winreg.OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE") # prepend unused variables with "dummy_" to keep PyLint happy dummy_n, v, dummy_t = winreg.EnumValue(aKey, 0) winreg.CloseKey(aKey) winreg.CloseKey(aReg) return v
def _get_msbuild(self): # 14.0 = VS2015 # 12.0 = VS2012 # 4.0 = VS2008 chk = ['14.0', '12.0', '4.0'] p = None for c in chk: p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\MSBuild\ToolsVersions\{}'.format(c), r'MSBuildToolsPath') if p is not None: break return os.path.join(p[0], 'MSBuild.exe') if p is not None else None
def _get_visual_studio_path(self): chk = ['14.0', '12.0', '4.0'] p = None for c in chk: p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\VisualStudio\{}'.format(c), r'ShellFolder') if p is not None: break return p[0] if p is not None else None
def _get_perl(self): p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\perl', 'BinDir') return p[0] if p is not None else None
def _get_nsis(self): p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS\Unicode', '') if p is None: p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS', '') return os.path.join(p[0], 'makensis.exe') if p is not None else None
def getWindowsEnvironmentKey(scope): assert scope in ('user', 'system') root = winreg.HKEY_CURRENT_USER subkey = 'Environment' if scope != 'user': root = winreg.HKEY_LOCAL_MACHINE subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' return (root, subkey)
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 _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PUTTY_is1", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\FileZilla Client", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def _getHiveAndKey(self, fullKey): '''Split a windows registry key in two parts: the hive (hkey) and the registry key Eg: "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" will return: (_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion") ''' str_hkey, str_key = fullKey.split('\\', 1) hiveType = WinRegHiveType.getByName(str_hkey.lower()) return hiveType.hive, str_key
def exportRegKeysToString(self, key): """Exports Windows registry key to a string This function exports a Windows registry key to a string (ini-file format). @param key: The registry key to export. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string """ strBuffer = StringIO() regfile = IniFile(strBuffer) self._addValuesRecursively(regfile, key) return regfile.getContent()
def exportRegKeysToFile(self, key, path): """Exports Windows registry key to a file This function exports a Windows registry key to an ini-file. @param key: The registry key to export. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string @param path: The path of the file to export to @type path: string """ j.sal.fs.writeFile(path, self.exportRegKeysToString(key))