Python winreg.CloseKey() Examples

The following are 30 code examples of winreg.CloseKey(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module winreg , or try the search function .
Example #1
Source File: nzblnkconfig.py    From nzb-monkey with MIT License 7 votes vote down vote up
def config_win():

    try:
        import winreg as reg
        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk')
        reg.SetValue(key, '', reg.REG_SZ, 'URL:nzblnk')
        reg.SetValueEx(key, 'URL Protocol', 0, reg.REG_SZ, '')
        reg.CloseKey(key)

        key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk\\shell\\open\\command')
        reg.SetValue(key, '', reg.REG_SZ, '"{0}" "%1"'.format(op.normpath(os.path.abspath(sys.executable))))
        reg.CloseKey(key)

    except (OSError, ImportError):
        print(Col.FAIL + ' FAILED to setup registry link for NZBLNK scheme!' + Col.OFF)
        sleep(wait_time)
        sys.exit(2) 
Example #2
Source File: mapiex.py    From nsf2x with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #3
Source File: test_command.py    From start_jupyter_cm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_run_command_windows(action):
    run_command(action=action)
    env_label = get_environment_label()

    import winreg
    if isadmin:
        h_key_base = winreg.HKEY_LOCAL_MACHINE
    else:
        h_key_base = winreg.HKEY_CURRENT_USER
    for terminal in ["qtconsole", "notebook", "lab"]:
        key = rf'Software\Classes\Directory\shell\jupyter_{terminal}_here{env_label.replace(" ", "_")}\Command'
        if action == "add" and shutil.which(f"jupyter-{terminal}") is not None:
            # Check if we can open the key to test if the key is present.
            registry_key = winreg.OpenKey(h_key_base, key)
            winreg.CloseKey(registry_key)
        else:
            with pytest.raises(FileNotFoundError):
                # If the key have been properly removed, we will expect
                # a `FileNotFoundError` to be raised
                winreg.OpenKey(h_key_base, key) 
Example #4
Source File: vmrun.py    From mech with MIT License 6 votes vote down vote up
def get_win32_executable():
    if PY3:
        import winreg
    else:
        import _winreg as winreg
    reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    try:
        key = winreg.OpenKey(reg, 'SOFTWARE\\VMware, Inc.\\VMware Workstation')
        try:
            return os.path.join(winreg.QueryValueEx(key, 'InstallPath')[0], 'vmrun.exe')
        finally:
            winreg.CloseKey(key)
    except WindowsError:
        key = winreg.OpenKey(reg, 'SOFTWARE\\WOW6432Node\\VMware, Inc.\\VMware Workstation')
        try:
            return os.path.join(winreg.QueryValueEx(key, 'InstallPath')[0], 'vmrun.exe')
        finally:
            winreg.CloseKey(key)
    finally:
        reg.Close()
    return get_fallback_executable() 
Example #5
Source File: animation.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _init_from_registry(cls):
        if sys.platform != 'win32' or rcParams[cls.exec_key] != 'convert':
            return
        import winreg
        for flag in (0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
            try:
                hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                        r'Software\Imagemagick\Current',
                                        0, winreg.KEY_QUERY_VALUE | flag)
                binpath = winreg.QueryValueEx(hkey, 'BinPath')[0]
                winreg.CloseKey(hkey)
                break
            except Exception:
                binpath = ''
        if binpath:
            for exe in ('convert.exe', 'magick.exe'):
                path = os.path.join(binpath, exe)
                if os.path.exists(path):
                    binpath = path
                    break
            else:
                binpath = ''
        rcParams[cls.exec_key] = rcParamsDefault[cls.exec_key] = binpath 
Example #6
Source File: animation.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _init_from_registry(cls):
        if sys.platform != 'win32' or rcParams[cls.exec_key] != 'convert':
            return
        import winreg
        for flag in (0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
            try:
                hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                        r'Software\Imagemagick\Current',
                                        0, winreg.KEY_QUERY_VALUE | flag)
                binpath = winreg.QueryValueEx(hkey, 'BinPath')[0]
                winreg.CloseKey(hkey)
                break
            except Exception:
                binpath = ''
        if binpath:
            for exe in ('convert.exe', 'magick.exe'):
                path = os.path.join(binpath, exe)
                if os.path.exists(path):
                    binpath = path
                    break
            else:
                binpath = ''
        rcParams[cls.exec_key] = rcParamsDefault[cls.exec_key] = binpath 
Example #7
Source File: msvs.py    From mbuild with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: animation.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def _init_from_registry(cls):
        if sys.platform != 'win32' or rcParams[cls.exec_key] != 'convert':
            return
        import winreg
        for flag in (0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
            try:
                hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE,
                                        r'Software\Imagemagick\Current',
                                        0, winreg.KEY_QUERY_VALUE | flag)
                binpath = winreg.QueryValueEx(hkey, 'BinPath')[0]
                winreg.CloseKey(hkey)
                break
            except Exception:
                binpath = ''
        if binpath:
            for exe in ('convert.exe', 'magick.exe'):
                path = os.path.join(binpath, exe)
                if os.path.exists(path):
                    binpath = path
                    break
            else:
                binpath = ''
        rcParams[cls.exec_key] = rcParamsDefault[cls.exec_key] = binpath 
Example #9
Source File: uninstall.py    From pyxll-examples with The Unlicense 6 votes vote down vote up
def uninstall_all():
    """uninstalls PyXLL from all installed Excel versions"""
    for wow64_flags in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
        for root in _root_keys.keys():
            try:
                flags = wow64_flags | winreg.KEY_READ
                office_root = winreg.OpenKey(root, r"Software\Microsoft\Office", 0, flags)
            except WindowsError:
                continue

            # look for all installed versions of Excel and uninstall PyXLL
            i = 0
            while True:
                try:
                    subkey = winreg.EnumKey(office_root, i)
                except WindowsError:
                    break

                match = re.match("^(\d+(?:\.\d+)?)$", subkey)
                if match:
                    office_version = match.group(1)
                    uninstall(office_root, office_version, wow64_flags)
                i += 1

            winreg.CloseKey(office_root) 
Example #10
Source File: Windows.py    From keyrings.alt with MIT License 6 votes vote down vote up
def _delete_key_if_empty(self, service):
        key_name = self._key_for_service(service)
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS
        )
        try:
            winreg.EnumValue(key, 0)
            return
        except WindowsError:
            pass
        winreg.CloseKey(key)

        # it's empty; delete everything
        while key_name != 'Software':
            parent, sep, base = key_name.rpartition('\\')
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER, parent, 0, winreg.KEY_ALL_ACCESS
            )
            winreg.DeleteKey(key, base)
            winreg.CloseKey(key)
            key_name = parent 
Example #11
Source File: helper.py    From skcom with MIT License 6 votes vote down vote up
def reg_list_value(key, root=winreg.HKEY_LOCAL_MACHINE):
    """
    列舉機碼下的所有值
    """
    i = 0
    values = {}
    handle = winreg.OpenKey(root, key)

    while True:
        try:
            (vname, value, _) = winreg.EnumValue(handle, i)
            if vname == '':
                vname = '(default)'
            values[vname] = value
            i += 1
        except OSError:
            # winreg.EnumValue(handle, i) 的 i 超出範圍
            break

    winreg.CloseKey(handle)
    return values 
Example #12
Source File: TaskManager.py    From Crypter with GNU General Public License v3.0 6 votes vote down vote up
def enable(self):
        '''
        @summary: Disables Windows Task Manager
        '''
        key_exists = False
        
        # Try to read the key
        try:
            reg = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION)
            disabled = winreg.QueryValueEx(reg, "DisableTaskMgr")[0]
            winreg.CloseKey(reg)
            key_exists = True
        except:
            pass
            
        # If key exists and is disabled, enable it
        if key_exists and disabled:
            reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                  self.DISABLE_KEY_LOCATION,
                                  0,
                                  winreg.KEY_SET_VALUE)
            winreg.SetValueEx(reg, "DisableTaskMgr", 0,  winreg.REG_DWORD, 0x00000000)
            winreg.CloseKey(reg) 
Example #13
Source File: sysproxy.py    From python-proxy with MIT License 6 votes vote down vote up
def __init__(self, args):
		self.listen = None
		for option in args.listen:
			protos = [x.name for x in option.protos]
			if option.unix or 'ssl' in protos or 'secure' in protos:
				continue
			if 'http' in protos:
				self.listen = option
				break
		if self.listen is None:
			print('No server listen on localhost by http')
		import winreg
		key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.KEY, 0, winreg.KEY_ALL_ACCESS)
		value, regtype = winreg.QueryValueEx(key, self.SUBKEY)
		assert regtype == winreg.REG_BINARY
		server = f'localhost:{self.listen.port}'.encode()
		bypass = '<local>'.encode()
		counter = int.from_bytes(value[4:8], 'little') + 1
		value = value[:4] + struct.pack('<III', counter, 3, len(server)) + server + struct.pack('<I', len(bypass)) + bypass + b'\x00'*36
		winreg.SetValueEx(key, self.SUBKEY, None, regtype, value)
		winreg.CloseKey(key) 
Example #14
Source File: Crypter.py    From Crypter with GNU General Public License v3.0 6 votes vote down vote up
def get_start_time(self):
        '''
        @summary: Get's Crypter's start time from the registry, or creates it if it
        doesn't exist
        @return: The time that the ransomware began it's encryption operation, in integer epoch form
        '''

        # Try to open registry key
        try:
            reg = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION)
            start_time = winreg.QueryValueEx(reg, "")[0]
            winreg.CloseKey(reg)
        # If failure, create the key
        except WindowsError:
            start_time = int(time.time())
            reg = winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION)
            winreg.SetValue(reg, "", winreg.REG_SZ, str(start_time))
            winreg.CloseKey(reg)

        return start_time 
Example #15
Source File: get_applications.py    From BoomER with GNU General Public License v3.0 6 votes vote down vote up
def get_apps_values(self, h_key, key_path):
        key = winreg.OpenKey(h_key, key_path, 0, winreg.KEY_READ)
        i = 0
        name = ""
        version = "???"
        while True:
            try:
                subkey = winreg.EnumValue(key, i)
                result = subkey[0]
                if result == "DisplayName":
                    name = subkey[1]
                elif result == "DisplayVersion":
                    version = subkey[1]
                i+=1
            except WindowsError as e:
                break
        if name != "":
            data = name + " ---> " + version
            print(data)
            if self.file_open:
                self.file_open.write(data + "\n")
        winreg.CloseKey(key) 
Example #16
Source File: installation.py    From dcs with GNU Lesser General Public License v3.0 6 votes vote down vote up
def is_using_dcs_standalone_edition():
    """
    Check if DCS World standalone edition is installed on this computer
    :return True if Standalone is installed, False if it is not
    """
    if not is_windows_os:
        return False
    try:
        dcs_path_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Eagle Dynamics\\DCS World")
        winreg.CloseKey(dcs_path_key)
        return True
    except FileNotFoundError as fnfe:
        try:
            dcs_path_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Eagle Dynamics\\DCS World OpenBeta")
            winreg.CloseKey(dcs_path_key)
            return True
        except FileNotFoundError:
            return False 
Example #17
Source File: installation.py    From dcs with GNU Lesser General Public License v3.0 6 votes vote down vote up
def is_using_dcs_steam_edition():
    """
    Check if DCS World : Steam Edition version is installed on this computer
    :return True if DCS Steam edition is installed,
            -1 if DCS Steam Edition is registered in Steam apps but not installed,
            False if never installed in Steam
    """
    if not is_windows_os:
        return False
    try:
        # Note : Steam App ID for DCS World is 223750
        dcs_steam_app_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Valve\\Steam\\Apps\\223750")
        installed = winreg.QueryValueEx(dcs_steam_app_key, "Installed")
        winreg.CloseKey(dcs_steam_app_key)
        if installed[0] == 1:
            return True
        else:
            return False
    except FileNotFoundError as fnfe:
        return False 
Example #18
Source File: regobj.py    From NVDARemote with GNU General Public License v2.0 6 votes vote down vote up
def flush(self):
        """Ensure that the key's data is flushed to disk.

        Quoting the _winreg documentation:

          It is not necessary to call FlushKey() to change a key. Registry
          changes are flushed to disk by the registry using its lazy flusher.
          Registry changes are also flushed to disk at system shutdown. 
          Unlike CloseKey(), the FlushKey() method returns only when all the
          data has been written to the registry. An application should only
          call FlushKey() if it requires absolute certainty that registry
          changes are on disk.

          If you don't know whether a FlushKey() call is required, it
          probably isn't.

        """
        _winreg.FlushKey(self.hkey) 
Example #19
Source File: img.py    From android_universal with MIT License 5 votes vote down vote up
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) 
Example #20
Source File: img.py    From diaphora with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #21
Source File: TaskManager.py    From Crypter with GNU General Public License v3.0 5 votes vote down vote up
def disable(self):
        '''
        @summary: Disables Windows Task Manager
        '''
        key_exists = False
        

        # Try to read the key
        try:
            reg = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION)
            disabled = winreg.QueryValueEx(reg, "DisableTaskMgr")[0]
            winreg.CloseKey(reg)
            key_exists = True
        except:
            pass
        
        # If key doesn't exist, create it and set to disabled
        if not key_exists:
            reg = winreg.CreateKey(winreg.HKEY_CURRENT_USER,
                                  self.DISABLE_KEY_LOCATION)
            winreg.SetValueEx(reg, "DisableTaskMgr", 0,  winreg.REG_DWORD, 0x00000001)
            winreg.CloseKey(reg)
        # If enabled, disable it
        elif key_exists and not disabled:
            reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                  self.DISABLE_KEY_LOCATION,
                                  0,
                                  winreg.KEY_SET_VALUE)
            winreg.SetValueEx(reg, "DisableTaskMgr", 0,  winreg.REG_DWORD, 0x00000001)
            winreg.CloseKey(reg) 
Example #22
Source File: img.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #23
Source File: img.py    From syntax-highlighting with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #24
Source File: recipe-577621.py    From code with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: img.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def _create_win(self):
        lookuperror = None
        keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
                     (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Fonts'),
                     (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
                     (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') ]
        for keyname in keynames:
            try:
                key = _winreg.OpenKey(*keyname)
                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']
                    return
                except FontNotFound as err:
                    lookuperror = err
                finally:
                    _winreg.CloseKey(key)
            except EnvironmentError:
                pass
        else:
            # If we get here, we checked all registry keys and had no luck
            # We can be in one of two situations now:
            # * All key lookups failed. In this case lookuperror is None and we
            #   will raise a generic error
            # * At least one lookup failed with a FontNotFound error. In this
            #   case, we will raise that as a more specific error
            if lookuperror:
                raise lookuperror
            raise FontNotFound('Can\'t open Windows font registry key') 
Example #26
Source File: Crypter.py    From Crypter with GNU General Public License v3.0 5 votes vote down vote up
def __add_to_startup_programs(self):
        '''
        @summary: Adds Crypter to the list of Windows startup programs
        @todo: Code and test
        @todo: Restore try and except catch
        '''

        try:
            reg = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION)
            winreg.SetValueEx(reg, "Crypter", 0, winreg.REG_SZ, sys.executable)
            winreg.CloseKey(reg)
        except WindowsError:
            pass 
Example #27
Source File: GXContext.py    From gxpy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_key_based_product_dirs(cls, key='Core', per_user_key=False):
        """
        Gets key product folders based on geosoft.key file and registry

        :param key:              Default Geosoft registry key (in absence of geosoft.key file) to use to discover GX
                                 developer common redistributables or Desktop Applications software (default 'Core')
        :param per_user_key:     Use per-user registry instead of local machine (default False)

        :returns: product_install_dir, user_dir, temp_dir

        .. versionadded:: 9.7
        """
        key_file = os.path.join(os.path.dirname(inspect.getfile(cls)), 'geosoft.key')
        if os.path.exists(key_file):
            with open(key_file) as f:
                key = f.read().strip()
        reg_hive = winreg.HKEY_CURRENT_USER if per_user_key else winreg.HKEY_LOCAL_MACHINE
        env_key = winreg.OpenKey(reg_hive, 'Software\Geosoft\{}\Environment'.format(key), 0,
                                 winreg.KEY_READ)
        try:
            product_install_dir, _ = winreg.QueryValueEx(env_key, 'GEOSOFT')
            user_dir, _ = winreg.QueryValueEx(env_key, 'GEOSOFT2')
            temp_dir, _ = winreg.QueryValueEx(env_key, 'GEOTEMP')
            return product_install_dir, user_dir, temp_dir
        finally:
            winreg.CloseKey(env_key) 
Example #28
Source File: helper.py    From skcom with MIT License 5 votes vote down vote up
def reg_find_value(key, value, root=winreg.HKEY_LOCAL_MACHINE):
    """
    遞迴搜尋機碼下的值, 回傳一組 tuple (所在位置, 數值)
    字串資料採用局部比對, 其餘型態採用完整比對
    """
    i = 0
    handle = winreg.OpenKey(root, key)
    vtype = type(value)

    while True:
        try:
            values = reg_list_value(key)
            for vname in values:
                # 型態不同忽略
                if not isinstance(values[vname], vtype):
                    continue

                leaf_node = key + ':' + vname
                if isinstance(value, str):
                    # 字串採用局部比對
                    if value in values[vname]:
                        return (leaf_node, values[vname])
                else:
                    # 其餘型態採用完整比對
                    if value == values[vname]:
                        return (leaf_node, values[vname])

            subkey = key + '\\' + winreg.EnumKey(handle, i)
            result = reg_find_value(subkey, value)
            if result[0] != '':
                return result

            i += 1
        except OSError:
            # winreg.EnumKey(handle, i) 的 i 超出範圍
            break

    winreg.CloseKey(handle)
    return ('', '') 
Example #29
Source File: helper.py    From skcom with MIT License 5 votes vote down vote up
def reg_read_value(node, root=winreg.HKEY_LOCAL_MACHINE):
    """
    讀取單一值
    """
    (key, name) = node.split(':')
    handle = winreg.OpenKey(root, key)
    (value, _) = winreg.QueryValueEx(handle, name)
    winreg.CloseKey(handle)
    return value 
Example #30
Source File: nsf2x.py    From nsf2x with GNU General Public License v2.0 5 votes vote down vote up
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