def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target = pythonw else: target = python key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, '"%s" -m fmpy.gui "%%1"' % target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e)
def test_CreateKey(self): from winreg import CreateKey, QueryInfoKey key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, "sub_key") nkeys, nvalues, since_mod = QueryInfoKey(key) assert nkeys == 1 nkeys, nvalues, since_mod = QueryInfoKey(sub_key) assert nkeys == 0
def __init__(self): self._MAIN = "SOFTWARE\\XIT" try: OpenKey(HKEY_CURRENT_USER, f"{self._MAIN}") except Exception as e: if (e.winerror != 2): InterfaceError("Failed to interact with Windows Registry") CreateKey(HKEY_CURRENT_USER, f"{self._MAIN}") CreateKey(HKEY_CURRENT_USER, f"{self._MAIN}\\USERS")
def test_SetValueEx(self): # this test leaves open keys. If it fails, others will too from winreg import CreateKey, SetValueEx, REG_BINARY, REG_DWORD key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, u"sub_key") SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, None) SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, 45) for name, value, type in self.test_data: SetValueEx(sub_key, name, 0, type, value) # cannot wrap a memoryview in setup_class for test_data SetValueEx(sub_key, u'test_name', None, REG_BINARY, memoryview(b'abc'))
def test_SetValueEx(self): from winreg import CreateKey, SetValueEx, REG_BINARY, REG_DWORD key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, "sub_key") SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, None) SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, 45) for name, value, type in self.test_data: SetValueEx(sub_key, name, 0, type, value) exc = raises(TypeError, SetValueEx, sub_key, 'test_name', None, REG_BINARY, memoryview('abc')) assert str(exc.value) == ("Objects of type 'memoryview' can not " "be used as binary registry values")
def Registrar(Action='get', RegPath='', RegName='', RegValue=''): ClassDict = {'HKEY_CURRENT_USER':HKEY_CURRENT_USER} mainkey = RegPath.split('\\')[0] RegRelativePath = RegPath.replace(mainkey + '\\', '') if Action == 'exists': try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: return(True) except FileNotFoundError: return(False) try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: if Action == 'get': value = QueryValueEx(key, RegName)[0] return(value) elif Action == 'set': SetValueEx(key, RegName, 0, REG_SZ, RegValue) if QueryValueEx(key, RegName)[0]: return(True) else: return(False) elif Action == 'setkey': CreateKey(ClassDict[mainkey], join(RegRelativePath, RegName)) except FileNotFoundError as regerr: pass
def Registrar(Action='get', RegPath='', RegName='', RegValue=''): try: ClassDict = { 'HKEY_LOCAL_MACHINE': HKEY_LOCAL_MACHINE, 'HKEY_CURRENT_USER': HKEY_CURRENT_USER, 'HKEY_USERS': HKEY_USERS, 'HKEY_CURRENT_CONFIG': HKEY_CURRENT_CONFIG } mainkey = RegPath.split('\\')[0] RegRelativePath = RegPath.replace(mainkey + '\\', '') with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: if Action == 'get': value = QueryValueEx(key, RegName)[0] return (value) elif Action == 'set': SetValueEx(key, RegName, 0, REG_SZ, RegValue) if QueryValueEx(key, RegName)[0]: return (True) else: return (False) elif Action == 'setkey': CreateKey(ClassDict[mainkey], RegRelativePath + '\\' + RegName) except FileNotFoundError as regerr: print(str(regerr))
def setup_module(machinery, name, path=None): if machinery.WindowsRegistryFinder.DEBUG_BUILD: root = machinery.WindowsRegistryFinder.REGISTRY_KEY_DEBUG else: root = machinery.WindowsRegistryFinder.REGISTRY_KEY key = root.format(fullname=name, sys_version='%d.%d' % sys.version_info[:2]) base_key = "Software\\Python\\PythonCore\\{}.{}".format( sys.version_info.major, sys.version_info.minor) assert key.casefold().startswith(base_key.casefold()), ( "expected key '{}' to start with '{}'".format(key, base_key)) try: with temp_module(name, "a = 1") as location: try: OpenKey(HKEY_CURRENT_USER, base_key) if machinery.WindowsRegistryFinder.DEBUG_BUILD: delete_key = os.path.dirname(key) else: delete_key = key except OSError: delete_key = base_key subkey = CreateKey(HKEY_CURRENT_USER, key) if path is None: path = location + ".py" SetValue(subkey, "", REG_SZ, path) yield finally: if delete_key: delete_registry_tree(HKEY_CURRENT_USER, delete_key)
def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey env = os.environ.get('CONDA_DEFAULT_ENV_') if env is None: python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): python = pythonw target = '"%s" -m fmpy.gui "%%1"' % python else: # activate the conda environment for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break windir = os.environ['WINDIR'] cmd = os.path.join(windir, 'System32', 'cmd.exe') target = r'%s /C ""%s" %s && python -m fmpy.gui %%1"' % (cmd, activate, env) key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e)
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 disablebUpdater(): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) bUpdater_key = OpenKeyEx( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0) except OSError: bUpdater_key = CreateKey( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0)
def set_reg(name, value): """Set DPI via registry key""" try: CreateKey(HKEY_CURRENT_USER, REG_PATH) registry_key = OpenKey(HKEY_CURRENT_USER, REG_PATH, 0, KEY_WRITE) SetValueEx(registry_key, name, 0, REG_SZ, value) CloseKey(registry_key) return True except: logger.exception("Exception occurred - Cannot Change DPI (set_reg)")
def write_destination_folder_to_reg( destination_folder: Path, reg_path: str = R'SOFTWARE\lyckantropen\moonlight_hdr_launcher' ) -> None: _logger.debug( f'Writing destination_folder="{destination_folder}" to registry at "{reg_path}"' ) CreateKey(HKEY_CURRENT_USER, reg_path) registry_key = OpenKey(HKEY_CURRENT_USER, reg_path, 0, KEY_WRITE) SetValueEx(registry_key, 'destination_folder', 0, REG_SZ, str(destination_folder)) CloseKey(registry_key)
def test_reflection_unsupported(self): import sys if sys.getwindowsversion() >= (5, 2): skip("Requires Windows XP") from winreg import (CreateKey, DisableReflectionKey, EnableReflectionKey, QueryReflectionKey, DeleteKeyEx) with CreateKey(self.root_key, self.test_key_name) as key: raises(NotImplementedError, DisableReflectionKey, key) raises(NotImplementedError, EnableReflectionKey, key) raises(NotImplementedError, QueryReflectionKey, key) raises(NotImplementedError, DeleteKeyEx, self.root_key, self.test_key_name)
def test_long_key(self): from winreg import (HKEY_CURRENT_USER, KEY_ALL_ACCESS, CreateKey, SetValue, EnumKey, REG_SZ, QueryInfoKey, OpenKey, DeleteKey) name = 'x' * 256 try: with CreateKey(HKEY_CURRENT_USER, self.test_key_name) as key: SetValue(key, name, REG_SZ, 'x') num_subkeys, num_values, t = QueryInfoKey(key) EnumKey(key, 0) finally: with OpenKey(HKEY_CURRENT_USER, self.test_key_name, 0, KEY_ALL_ACCESS) as key: DeleteKey(key, name) DeleteKey(HKEY_CURRENT_USER, self.test_key_name)
def setup_module(machinery, name, path=None): if machinery.WindowsRegistryFinder.DEBUG_BUILD: root = machinery.WindowsRegistryFinder.REGISTRY_KEY_DEBUG else: root = machinery.WindowsRegistryFinder.REGISTRY_KEY key = root.format(fullname=name, sys_version=sys.version[:3]) try: with temp_module(name, "a = 1") as location: subkey = CreateKey(HKEY_CURRENT_USER, key) if path is None: path = location + ".py" SetValue(subkey, "", REG_SZ, path) yield finally: if machinery.WindowsRegistryFinder.DEBUG_BUILD: key = os.path.dirname(key) delete_registry_tree(HKEY_CURRENT_USER, key)
def writeRegistry(self, myKey, value): REG_PATH = 'SOFTWARE\ABB\PythonTestRunner' try: keyval = r'SOFTWARE\ABB\PythonTestRunner' if not os.path.exists("keyval"): CreateKey(HKEY_LOCAL_MACHINE, keyval) Registrykey = OpenKey(HKEY_LOCAL_MACHINE, REG_PATH, 0, KEY_WRITE) SetValueEx(Registrykey, myKey, 0, REG_SZ, value) CloseKey(Registrykey) return True except Exception as e: print( "While attempting to write a registry key, the following error occurred:\n" + str(e) + "\nThis is likely because this user account does not have admin rights or Python Test Runner has not been run as administrator.\n" ) return False
def changeTheme(theme): """This changes the Windows 10 app theme to light or dark. Args: theme (Theme | bool): Either LIGHT (True) or dark DARK (False) """ from winreg import OpenKey, SetValueEx, QueryValueEx, CloseKey, CreateKey, HKEY_CURRENT_USER, KEY_ALL_ACCESS, REG_DWORD if type(theme) is Theme: theme = theme.value value = 1 if theme else 0 keyPath = r'Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' try: key = OpenKey(HKEY_CURRENT_USER, keyPath, 0, KEY_ALL_ACCESS) except: key = CreateKey(HKEY_CURRENT_USER, keyPath) if QueryValueEx(key, 'AppsUseLightTheme')[0] != value: SetValueEx(key, 'AppsUseLightTheme', 0, REG_DWORD, value) CloseKey(key)
class UserEnv: REG_PATH = r'Environment' ENV = CreateKey(HKEY_CURRENT_USER, REG_PATH) def __init__(self, key): self.key = key def open_key(self, open_type): return OpenKey(HKEY_CURRENT_USER, self.REG_PATH, 0, open_type) def set(self, value): key = self.open_key(KEY_WRITE) SetValueEx(key, self.key, 0, REG_SZ, value) CloseKey(key) 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 persistance(name, path): # if the path is a directory then add explorer to permit the opening if path.find('.') == -1 and name != path: path = "explorer " + path # replace the double anti slashes by one path = path.replace('\\\\', '\\') # create a key in register CreateKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run') # open the key in register key = OpenKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_SET_VALUE) # add the value in the key # key is the path in the register # name is the name of new key # path is the path of new key SetValueEx(key, name, 0, REG_SZ, path) # close key key.Close() print("The " + name + " in " + path + " Launch in the next Boot.")
if want_custom: command = input("Paste your custom command: ") else: print("Continuing with defaults.") ################# # Create and open registry keys ################# print("Creating and opening the required registry keys...") reg = ConnectRegistry(None, HKEY_CURRENT_USER) shell_key = r"Software\Classes\*\shell" pylinx_shell_key = r"Software\Classes\*\shell\pylinx" pylinx_command_key = r"Software\Classes\*\shell\pylinx\command" reg_pylinx_shell_key = CreateKey(reg, pylinx_shell_key) reg_pylinx_command_key = CreateKey(reg, pylinx_command_key) # Edit registry to add an element to the context menu print("Editing key values...") SetValueEx(reg_pylinx_shell_key, "", None, REG_SZ, "Upload file with pylinx") SetValueEx(reg_pylinx_shell_key, "icon", None, REG_SZ, ASSETS_ICO) SetValueEx(reg_pylinx_command_key, "", None, REG_SZ, command) # Close all handles print("Closing key handles...") reg_pylinx_shell_key.Close() reg_pylinx_command_key.Close()
def windows_registry_set_key(key_path, value): from winreg import CreateKey, SetValue, HKEY_CURRENT_USER, REG_SZ with CreateKey(HKEY_CURRENT_USER, key_path) as sub_key: SetValue(sub_key, None, REG_SZ, value)
def write_path_to_reg(destination_folder: Path, reg_path: str, reg_key: str) -> None: CreateKey(HKEY_CURRENT_USER, reg_path) registry_key = OpenKey(HKEY_CURRENT_USER, reg_path, 0, KEY_WRITE) SetValueEx(registry_key, reg_key, 0, REG_SZ, str(destination_folder)) CloseKey(registry_key)
def create_keys(): CreateKey(HKEY_CURRENT_USER, "SOFTWARE\\Wine") for key in REG_KEYS: CreateKey(HKEY_LOCAL_MACHINE, key) print_log("Creating fake registry key : " + key)
def __init__(self) -> None: """Create and open the key.""" self._open = CreateKey(HKEY_CURRENT_USER, consts.REG_KEY_RUN)