def _FindDatabaseFolder(self, wechat_id): """取默认数据库存放路径""" key_handle = OpenKey(HKEY_CURRENT_USER, r"Software\Tencent\WeChat") folder, _ = QueryValueEx(key_handle, 'FileSavePath') CloseHandle(key_handle) if folder == 'MyDocument:': folder = self._FindMyDocPath() return os.path.join(folder, 'WeChat Files', wechat_id, 'Msg')
def Registrar(RegPath='', RegName=''): try: with OpenKey(HKEY_CURRENT_USER, RegPath, 0, KEY_ALL_ACCESS) as key: value = QueryValueEx(key, RegName)[0] return (value) except FileNotFoundError as regerr: return ('') pass
def get_env(name, user=True): root, subkey = env_keys(user) key = OpenKey(root, subkey, 0, KEY_READ) try: value, _ = QueryValueEx(key, name) except WindowsError: return '' return value
def soft_audit(self, work_id): soft = list() if platform.system() == 'Windows': from winreg import HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, OpenKey, QueryValueEx, EnumKey keyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" aKey = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_ALL_ACCESS) i = 0 exception = False while not exception: try: subkey = EnumKey(aKey, i) path = keyPath + "\\" + subkey key = OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS) try: display_name = str(QueryValueEx(key, 'DisplayName')[0]) try: display_version = str( QueryValueEx(key, 'DisplayVersion')[0]) except: display_version = '' try: install_location = str( QueryValueEx(key, 'InstallLocation')[0]) except: install_location = '' try: install_date = str( QueryValueEx(key, 'InstallDate')[0]) except: install_date = '' soft.append({ 'display_version': display_version.replace('\'', '\'\'\''), 'display_name': display_name.replace('\'', '\'\'\''), 'install_location': install_location.replace('\'', '\'\'\''), 'install_date': install_date }) except: pass except: exception = True i += 1 self.saudit = {'datasoft': soft, 'softaudit': True, 'work_id': work_id}
def check_R_dependency(): updated = False r_installfold = read_setting('Processing/Configuration/R_FOLDER') if platform.system() == 'Windows': try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\R-core\R") aVal = os.path.normpath(QueryValueEx(aKey, "InstallPath")[0]) if os.path.exists(aVal): if r_installfold is not None and r_installfold != aVal: r_installfold = aVal write_setting('Processing/Configuration/R_FOLDER', aVal) LOGGER.info( 'Setting ... R Install folder: {}'.format(aVal)) r_installed = True except EnvironmentError: r_installed = False write_setting('Processing/Configuration/R_FOLDER', '') write_setting('Processing/Configuration/ACTIVATE_R', False) return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' else: # Linux/OSX - https://stackoverflow.com/a/25330049 try: subprocess.check_call(['which', 'R']) except subprocess.CalledProcessError: r_installed = False else: r_installed = True if not r_installed: write_setting('Processing/Configuration/R_FOLDER', '') write_setting('Processing/Configuration/ACTIVATE_R', False) return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' # Get the users R script folder - returns none if not set. r_scripts_fold = read_setting('Processing/Configuration/R_SCRIPTS_FOLDER') if r_scripts_fold is None: return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' files = glob.glob(os.path.join(PLUGIN_DIR, "R-Scripts", "*.rsx")) files += glob.glob(os.path.join(PLUGIN_DIR, "R-Scripts", "*.rsx.help")) for src_file in files: dest_file = os.path.join(r_scripts_fold, os.path.basename(src_file)) # only copy if it doesn't exist or it is newer by 1 second. if not os.path.exists(dest_file) or os.stat( src_file).st_mtime - os.stat(dest_file).st_mtime > 1: shutil.copy2(src_file, dest_file) updated = True if updated: LOGGER.info('Updating Whole-of-block analysis tool.') return True
def _FindMyDocPath(self): """取得“我的文档”的路径""" key_handle = OpenKey( HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) path, _ = QueryValueEx(key_handle, 'Personal') CloseHandle(key_handle) return path
def get(self, default=None): key = self.open_key(KEY_READ) try: value, regtype = QueryValueEx(key, self.key) except FileNotFoundError: value = default CloseKey(key) return value
def get_steam_directory(): if platform.system() == 'Windows': from winreg import QueryValueEx, HKEY_CURRENT_USER, CreateKey key = CreateKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam") return QueryValueEx(key, "SteamPath")[0] elif platform.system() == 'Linux': return '~/.local/share/Steam' else: raise Exception("Unsupported OS")
def add2Registery(filePath): runSubKey = r"Software\Microsoft\Windows\CurrentVersion\Run" with OpenKey(HKEY_LOCAL_MACHINE, runSubKey, 0, KEY_ALL_ACCESS) as regObject: try: QueryValueEx(regObject, 'MSdefender') except: SetValueEx(regObject, "MSdefender", 0, REG_SZ, filePath)
def get_processor_name(): from winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE registry_connection = ConnectRegistry(None, HKEY_LOCAL_MACHINE) registry_key = OpenKey( registry_connection, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") name = QueryValueEx(registry_key, 'ProcessorNameString')[0] return name
def read_reg_key(root, key, value): try: with OpenKey(root, key, access=KEY_READ | KEY_WOW64_64KEY) as key_handle: current_version, _ = QueryValueEx(key_handle, value) return current_version except OSError as error: logger.error(f"Could not find registry key {key}") return None
def _get_clock_ghz_windows() -> float: from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(registry, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") mhz, _ = QueryValueEx(key, "~MHz") ghz = mhz_to_ghz(check_cast(float, mhz)) assert 0 < ghz < 10 return ghz
def check_registry_key(java_key): """ Method checks for the java in the registry entries. """ from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, \ QueryValueEx path = None try: a_reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) r_key = OpenKey(a_reg, java_key) for i_cnt in range(1024): current_version = QueryValueEx(r_key, "CurrentVersion") if current_version: key = OpenKey(r_key, current_version[0]) if key: path = QueryValueEx(key, "JavaHome") return path[0] except Exception: ImcWarning("Not able to access registry.") return None
def get_package_version(name): name_re = re.compile(name) for products in regedit_products: i = 0 while True: try: product_key_name = EnumKey(products, i) except OSError as e: break product_values = OpenKey(products, product_key_name) try: display_name = QueryValueEx(product_values, 'DisplayName')[0] if name_re.findall(display_name): return QueryValueEx(product_values, 'DisplayVersion')[0] except FileNotFoundError: # product has no 'DisplayName' attribute pass i += 1 raise RuntimeError(f'Package {name} version not found')
def __find_store(self): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) base_key = OpenKeyEx(root, EGS.LAUNCHER_PATH) data_path = QueryValueEx(base_key, "AppDataPath") self.__valid = True return data_path[0] except Exception as e: self.__context.warn( "Failed to find path, maybe it isn't installed", e)
def getSynthRiderInstallFolder(): try: registry_key = OpenKey( HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 885000', 0, KEY_READ) value, _ = QueryValueEx(registry_key, r'InstallLocation') CloseKey(registry_key) return value except WindowsError: return None
def test_dynamic_key(self): from winreg import EnumValue, QueryValueEx, HKEY_PERFORMANCE_DATA try: EnumValue(HKEY_PERFORMANCE_DATA, 0) except WindowsError as e: import errno if e.errno in (errno.EPERM, errno.EACCES): skip("access denied to registry key " "(are you running in a non-interactive session?)") raise QueryValueEx(HKEY_PERFORMANCE_DATA, None)
def __get_exe_path(self): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) base_key = OpenKeyEx(root, EGS.ICON_PATH) data_path = QueryValueEx(base_key, "") self.__context.dbg("data path", data_path) self.__valid = True return data_path[0].split(",")[0] except Exception as e: self.__context.warn( "Failed to find executable, maybe it isn't installed", e)
def sys_bgcolor(pyplot): """Reads system preference and sets plt background accordingly""" from winreg import ConnectRegistry, HKEY_CURRENT_USER, OpenKeyEx, QueryValueEx root = ConnectRegistry(None, HKEY_CURRENT_USER) policy_key = OpenKeyEx( root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize") light, _ = QueryValueEx(policy_key, "AppsUseLightTheme") if light: pyplot.style.use('default') else: pyplot.style.use('dark_background')
def _v(key, value_name): result = None key_id = id(key) try: result = QueryValueEx(key, value_name) return result except Exception as exception: result = exception raise result finally: value_collect[key_id][value_name] = result
def _get_clock_ghz_windows() -> float: # Import lazily as this is only available on Windows # pylint:disable=import-outside-toplevel from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(registry, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") mhz, _ = QueryValueEx(key, "~MHz") ghz = mhz_to_ghz(check_cast(float, mhz)) assert 0 < ghz < 10 return ghz
def _get_value(hive: int, key: str, value: Optional[str], arch: int) -> str: try: open_reg = ConnectRegistry(None, hive) open_key = OpenKey(open_reg, key, 0, KEY_READ | arch) value, key_type = QueryValueEx(open_key, value) # Return the first match return value except (FileNotFoundError, TypeError, OSError) as exc: raise FileNotFoundError( 'Registry key [%s] with value [%s] not found. %s' % (key, value, exc))
def get_registry_key_value(HKEYS, key, value): HANDLES = { "CLASSES_ROOT": winreg.HKEY_CLASSES_ROOT, "CURRENT_USER": winreg.HKEY_CURRENT_USER, "LOCAL_MACHINE": winreg.HKEY_LOCAL_MACHINE, "USERS": winreg.HKEY_USERS, "PERFORMANCE_DATA": winreg.HKEY_PERFORMANCE_DATA, "CURRENT_CONFIG": winreg.HKEY_CURRENT_CONFIG } key = key.replace('/', '\\') return QueryValueEx(OpenKey(ConnectRegistry(None, HANDLES[HKEYS]), key), value)
def get_from_hklm(hkey ,path, name, wow64=False): from winreg import QueryValueEx, OpenKey, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY flags = KEY_READ if wow64: flags |= KEY_WOW64_32KEY # avoids crashing if a product is not present try: with OpenKey(HKEY_LOCAL_MACHINE if hkey == "HKEY_LOCAL_MACHINE" else HKEY_CURRENT_USER, path, 0, flags) as key: return QueryValueEx(key, name)[0] except Exception: return None
def check_setting(): try: with OpenKey(HKEY_LOCAL_MACHINE, AU, 0, KEY_READ) as key: try: noautoupdate = QueryValueEx(key, NoAutoUpdate)[0] except FileNotFoundError: noautoupdate = False if noautoupdate: auoption = 1 else: auoption = QueryValueEx(key, AUOptions)[0] if 1 <= auoption <= 4: print(f'Your machine is on setting "{auoption}"') else: print('Your machine is on an unrecognized setting') except FileNotFoundError: # If either the key or AUOptions doesn't exist print('Your machine is on the default setting ("0")') print()
def toggle_color_mode(): """Toggles system color scheme preference.""" from winreg import ConnectRegistry, HKEY_CURRENT_USER, REG_SZ, KEY_ALL_ACCESS, OpenKeyEx, QueryValueEx, SetValueEx, CloseKey root = ConnectRegistry(None, HKEY_CURRENT_USER) policy_key = OpenKeyEx( root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize", access=KEY_ALL_ACCESS) light, _ = QueryValueEx(policy_key, "AppsUseLightTheme") SetValueEx(policy_key, "AppsUseLightTheme", 0, REG_SZ, str(1 - int(light))) SetValueEx(policy_key, "SystemUsesLightTheme", 0, REG_SZ, str(1 - int(light))) CloseKey(policy_key)
def find_msys2_cairo(cairo): swpath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" for root in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]: with OpenKey(root, swpath) as swkey: keys, _, _ = QueryInfoKey(swkey) for i in range(0, keys): subpath = EnumKey(swkey, i) with OpenKey(root, swpath + "\\" + subpath) as subkey: try: name, _ = QueryValueEx(subkey, 'DisplayName') loc, _ = QueryValueEx(subkey, 'InstallLocation') if name.startswith('MSYS2'): dirs = [ d for d in listdir(loc) if isdir(join(loc, d)) ] for d in dirs: libdir = join(loc, d, 'bin') if exists(join(libdir, cairo)): return libdir except: pass return False
def windows_group_policy_path(): from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKeyEx, QueryValueEx, REG_EXPAND_SZ, REG_SZ try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) policy_key = OpenKeyEx(root, r"SOFTWARE\Policies\Google\Chrome") user_data_dir, type_ = QueryValueEx(policy_key, "UserDataDir") if type_ == REG_EXPAND_SZ: user_data_dir = os.path.expandvars(user_data_dir) elif type_ != REG_SZ: return None except OSError: return None return os.path.join(user_data_dir, "Default", "Cookies")
def is_dir(self, path): localPath = path.replace("/", "\\") rootKey = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(rootKey, localPath) return True except EnvironmentError: pass parent = dirname(path).replace("/", "\\") valueName = basename(path) key = OpenKey(rootKey, parent) value = QueryValueEx(key, valueName) return False
def isLightMode_Windows() -> bool: # pylint: disable=invalid-name """For Windows OS MIT clxmente (https://github.com/clxmente/Windows-Dark-Mode-Check) Returns: bool: Windows is in light mode """ from winreg import HKEY_CURRENT_USER, ConnectRegistry, OpenKey, QueryValueEx keyAt = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize" registryHive = ConnectRegistry(None, HKEY_CURRENT_USER) openedKey = OpenKey(registryHive, keyAt) return QueryValueEx(openedKey, "AppsUseLightTheme")[0] != 0
if __name__ == '__main__': parser = ArgumentParser(prog='pathx') parser.add_argument('action', type=action, help='action to preform on %%PATH%% (APPEND, PREPEND, REMOVE)') parser.add_argument('pathname', type=directory, help='pathname to add to or remove from %%PATH%%') parser.add_argument('-S', '--system', action='store_true', help='preform action on system %%PATH%% instead of user %%PATH%%') args = parser.parse_args() registry_location = HKEY_CURRENT_USER sub_key = 'Environment' if args.system: registry_location = HKEY_LOCAL_MACHINE sub_key = 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment' with OpenKey(registry_location, sub_key, access=KEY_ALL_ACCESS) as environment_key: # open registry location path_value_list = QueryValueEx(environment_key, 'Path')[0].split(';') # get and split values in current path value try: path_value_list.remove(args.pathname) # removes the pathname from the current path value except Exception: pass finally: if args.action == 'APPEND': path_value_list.append(args.pathname) # appends pathname to path elif args.action == 'PREPEND': path_value_list = [args.pathname] + path_value_list # prepend pathname to path SetValueEx(environment_key, 'Path', 0, REG_SZ, ';'.join(path_value_list)) # write path back to registry