我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用winreg.OpenKey()。
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 _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir
def is_autostart_enabled(self): if os.name == 'nt': with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self._windows_run_reg_key, 0, winreg.KEY_ALL_ACCESS) as key: try: reg_value, reg_type = winreg.QueryValueEx(key, const.APP_NAME) if reg_type == winreg.REG_SZ and reg_value == self._get_executable_path(): return True else: try: winreg.DeleteValue(key, self.WIN_REG_AUTORUN_KEY) except OSError: pass # key does not exist except: return False else: return os.path.exists(self._linux_autostart_file)
def test_get_home_dir_8(): """Using registry hack for 'My Documents', os=='nt' HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. """ os.name = 'nt' # Remove from stub environment all keys that may be set for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: env.pop(key, None) class key: def Close(self): pass with patch.object(wreg, 'OpenKey', return_value=key()), \ patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]): home_dir = path.get_home_dir() nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
def _RegistryGetValueUsingWinReg(key, value): """Use the _winreg module to obtain the value of a registry key. Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure. Throws ImportError if _winreg is unavailable. """ try: import _winreg except ImportError: import winreg as _winreg try: root, subkey = key.split('\\', 1) assert root == 'HKLM' # Only need HKLM for now. with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey: return _winreg.QueryValueEx(hkey, value)[0] except WindowsError: return None
def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ import winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") dir, type = winreg.QueryValueEx(key, shell_folder_name) return dir
def get_steam_path(): """Get the path for Steam from the Steam process. If that fails, it uses the registry on Windows. Returns: str: The path to Steam. If the path could not be found, the current directory is returned instead (os.curdir) """ if psutil: for pid in psutil.process_iter(): try: if pid.name().lower() == 'steam.exe' or pid.name().lower() == 'steam': return os.path.dirname(pid.exe()) except psutil.Error: logger.exception("Could not get Steam path from its process.") if winreg: try: reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Valve\Steam') return os.path.normpath(winreg.QueryValueEx(reg_key, r'SteamPath')[0]) except WindowsError: logger.exception("Could not query registry for Steam path") return os.curdir
def get_home_dir(self, username): """Return the user's profile directory, the closest thing to a user home directory we have on Windows. """ try: sid = win32security.ConvertSidToStringSid( win32security.LookupAccountName(None, username)[0]) except pywintypes.error as err: raise AuthorizerError(err) path = r"SOFTWARE\Microsoft\Windows NT" \ r"\CurrentVersion\ProfileList" + "\\" + sid try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise AuthorizerError( "No profile directory defined for user %s" % username) value = winreg.QueryValueEx(key, "ProfileImagePath")[0] home = win32api.ExpandEnvironmentStrings(value) if not PY3 and not isinstance(home, unicode): home = home.decode('utf8') return home
def CoCreateInstanceC2R (self, store, reg, clsid, iid) : # Ugly code to find DLL in C2R version of COM object and get a COM # object despite the fact that COM doesn't handle C2R try: # Get DLL to load from 2R register aReg = winreg.ConnectRegistry(None, store) aKey = winreg.OpenKey(aReg, reg, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) dummy_n, IconvDLL, dummy_t = winreg.EnumValue(aKey, 0) winreg.CloseKey(aKey) winreg.CloseKey(aReg) # Create OLE object from DLL IconvOLE = ctypes.OleDLL(IconvDLL) # Get COM Instance from OLE clsid_class = uuid.UUID(str(clsid)).bytes_le iclassfactory = uuid.UUID(str(pythoncom.IID_IClassFactory)).bytes_le com_classfactory = ctypes.c_long(0) IconvOLE.DllGetClassObject(clsid_class, iclassfactory, ctypes.byref(com_classfactory)) MyFactory = pythoncom.ObjectFromAddress(com_classfactory.value, pythoncom.IID_IClassFactory) return MyFactory.CreateInstance (None, str(iid)) except: return None
def getEnvironment(scope, name): assert scope in ('user', 'system') value = '' if platform.system() == 'Windows': root, subkey = getWindowsEnvironmentKey(scope) key = winreg.OpenKey(root, subkey, 0, winreg.KEY_READ) try: value, _ = winreg.QueryValueEx(key, name) except WindowsError: value = '' else: if name.lower() == 'uid': return str(os.geteuid()) if len(os_user_name) > 0: ret, cret = syscommand('su -l %s -c \'echo ${%s}\'' % (os_user_name, name), True) if len(ret) > 0: value = ret[0].strip() else: value = os.environ.get(name, "") return value
def proxy_bypass_registry(host): if is_py3: import winreg else: import _winreg as winreg try: internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') proxyEnable = winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0] proxyOverride = winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0] except OSError: return False if not proxyEnable or not proxyOverride: return False # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') # now check if we match one of the registry values. for test in proxyOverride: if test == '<local>': if '.' not in host: return True test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char if re.match(test, host, re.I): return True return False
def _save_autostart_win(self, on): with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self._windows_run_reg_key, 0, winreg.KEY_ALL_ACCESS) as key: if on: winreg.SetValueEx(key, const.APP_NAME, 0, winreg.REG_SZ, self._get_executable_path()) else: try: winreg.DeleteValue(key, const.APP_NAME) except OSError: pass # key does not exist
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 locate_docpath(): addon_prefs = bpy.context.user_preferences.addons[__package__].preferences # Use the system preference if its set. pov_documents = addon_prefs.docpath_povray if pov_documents: if os.path.exists(pov_documents): return pov_documents else: print("User Preferences path to povray documents %r NOT FOUND, checking $PATH" % pov_documents) # Windows Only if sys.platform[:3] == "win": import winreg try: win_reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\POV-Ray\\v3.7\\Windows") win_docpath = winreg.QueryValueEx(win_reg_key, "DocPath")[0] pov_documents = os.path.join(win_docpath, "Insert Menu") if os.path.exists(pov_documents): return pov_documents except FileNotFoundError: return"" # search the path all os's pov_documents_default = "include" os_path_ls = os.getenv("PATH").split(':') + [""] for dir_name in os_path_ls: pov_documents = os.path.join(dir_name, pov_documents_default) if os.path.exists(pov_documents): return pov_documents return ""
def findTesserAct(default="C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe"): """Search for Tesseract exceutable via registry.""" if(not windows): return default try: import winreg key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Tesseract-OCR") return winreg.QueryValueEx(key, "Path")[0] + '\\tesseract.exe' except: return default
def getenv(self, name): key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ) try: value, _ = winreg.QueryValueEx(key, name) except WindowsError: value = '' winreg.CloseKey(key) return value
def setenv(self, name, value): # Note: for 'system' scope, you must run this as Administrator key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value) winreg.CloseKey(key) # For some strange reason, calling SendMessage from the current process # doesn't propagate environment changes at all. # TODO: handle CalledProcessError (for assert) check_call('''\ "%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
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