我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用winreg.QueryValueEx()。
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 _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 _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 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 _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 get_proxy_state(): AutoConfigURL = ProxyServer = None try: AutoConfigURL, reg_type = winreg.QueryValueEx(SETTINGS, 'AutoConfigURL') AutoConfigURL = proxy_server(AutoConfigURL) except: pass try: ProxyEnable, reg_type = winreg.QueryValueEx(SETTINGS, 'ProxyEnable') if ProxyEnable: ProxyServer, reg_type = winreg.QueryValueEx(SETTINGS, 'ProxyServer') ProxyServer = proxy_server(ProxyServer) except: pass if AutoConfigURL and ProxyServer: ProxyServer.pac = AutoConfigURL.pac ProxyServer.type |= 1 elif AutoConfigURL: ProxyServer = AutoConfigURL elif ProxyServer: pass else: ProxyServer = proxy_server(None) return ProxyServer
def get_password(self, service, username): """Get password of the username for the service """ try: # fetch the password key = r'Software\%s\Keyring' % service hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) password_saved = winreg.QueryValueEx(hkey, username)[0] password_base64 = password_saved.encode('ascii') # decode with base64 password_encrypted = base64.decodestring(password_base64) # decrypted the password password = _win_crypto.decrypt(password_encrypted).decode('utf-8') except EnvironmentError: password = None return password
def _read_registry(root,key,value): if _is_py2: import _winreg as winreg else: import winreg try: hkey = winreg.OpenKey(root, key) except: return None try: (val, typ) = winreg.QueryValueEx(hkey, value) except: winreg.CloseKey(hkey) return None winreg.CloseKey(hkey) return val
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 _lookup_win(self, key, basename, styles, fail=False): for suffix in ('', ' (TrueType)'): for style in styles: try: valname = '%s%s%s' % (basename, style and ' '+style, suffix) val, _ = _winreg.QueryValueEx(key, valname) return val except EnvironmentError: continue else: if fail: raise FontNotFound('Font %s (%s) not found in registry' % (basename, styles[0])) return None
def _config_win32_fromkey(self, key): """Extract DNS info from a registry key.""" try: servers, rtype = _winreg.QueryValueEx(key, 'NameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'Domain') if dom: self._config_win32_domain(dom) except WindowsError: pass else: try: servers, rtype = _winreg.QueryValueEx(key, 'DhcpNameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'DhcpDomain') if dom: self._config_win32_domain(dom) except WindowsError: pass try: search, rtype = _winreg.QueryValueEx(key, 'SearchList') except WindowsError: search = None if search: self._config_win32_search(search)
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