Python winreg.HKEY_LOCAL_MACHINE Examples

The following are 30 code examples of winreg.HKEY_LOCAL_MACHINE(). 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: __init__.py    From browser_cookie3 with GNU Lesser General Public License v3.0 7 votes vote down vote up
def windows_group_policy_path():
    # we know that we're running under windows at this point so it's safe to do these imports
    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")


# Code adapted slightly from https://github.com/Arnie97/chrome-cookies 
Example #2
Source File: _core.py    From photoshop-python-api with MIT License 7 votes vote down vote up
def open_key(key):
        """Open the register key.

        Args:
            key (str): The key of register.

        Returns:
            str: The handle to the specified key.

        """
        machine_type = platform.machine()
        mappings = {"AMD64": winreg.KEY_WOW64_64KEY}
        return winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            key,
            access=winreg.KEY_READ | mappings.get(machine_type,
                                                  winreg.KEY_WOW64_32KEY),
        ) 
Example #3
Source File: store_env_in_registry.py    From coala-quickstart with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_envvar_in_registry(envvar, value):
    try:
        import winreg
    except ImportError:
        import _winreg as winreg

    reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    with winreg.OpenKey(reg, KEY, 0, winreg.KEY_ALL_ACCESS) as regkey:
        winreg.SetValueEx(regkey, envvar, 0, winreg.REG_EXPAND_SZ, value) 
Example #4
Source File: font_manager.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given. Additionally, it is searched for user
    fonts installed. A list of TrueType font filenames are returned by default,
    or AFM fonts if *fontext* == 'afm'.
    """
    import winreg

    if directory is None:
        directory = win32FontDirectory()

    fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]

    items = set()

    # System fonts
    items.update(_win32RegistryFonts(winreg.HKEY_LOCAL_MACHINE, directory))

    # User fonts
    for userdir in MSUserFontDirectories:
        items.update(_win32RegistryFonts(winreg.HKEY_CURRENT_USER, userdir))

    # Keep only paths with matching file extension.
    return [str(path) for path in items if path.suffix.lower() in fontext] 
Example #5
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 #6
Source File: win_sec_check.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def QueryAutoCdRom():
	keypath=r'SYSTEM\CurrentControlSet\Services\cdrom'
	try:
		key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,keypath)
		return  _winreg.QueryValueEx(key,'AutoRun')[0]
	except:
		return None

# def QueryHKCUNoDriveAutoRun():# 0-0x3FFFFFF 
# 	keypath=r'Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
# 	try:
# 		key=_winreg.OpenKey(_winreg.HKEY_CURRENT_USER,keypath)
# 		return  _winreg.QueryValueEx(key,'NoDriveAutoRun ')[0]
# 	except:
# 		return None

# def QueryHKCUNoDriveTypeAutoRun():
# 	keypath=r'Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
# 	try:
# 		key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,keypath)
# 		return  _winreg.QueryValueEx(key,'NoDriveTypeAutoRun ')[0]
# 	except:
# 		return None 
Example #7
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 #8
Source File: QgsFmvInstaller.py    From QGISFMV with GNU General Public License v3.0 6 votes vote down vote up
def IsLavFilters():
    ''' Check if LavFilters is present '''
    if windows:
        software_list = WinSoftwareInstalled(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY) + WinSoftwareInstalled(winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY) + WinSoftwareInstalled(winreg.HKEY_CURRENT_USER, 0)
        if not any('LAV Filters' in software['name'] for software in software_list):
            # does not exist
            return False
    else:
        cache = apt.Cache()
        cache.open()
        try:
            #print("lav filters")
            return cache["gst123"].is_installed
        except Exception:
            # does not exist
            return False
    return True 
Example #9
Source File: msvs.py    From mbuild with Apache License 2.0 6 votes vote down vote up
def _find_msvc_in_registry(env,version):
    if _is_py2:
        import _winreg as winreg
    else:
        import winreg

    vs_ver = str(version) + '.0'
    vs_key = 'SOFTWARE\\Microsoft\\VisualStudio\\' + vs_ver + '\\Setup\\VS'
    vc_key = 'SOFTWARE\\Microsoft\\VisualStudio\\' + vs_ver + '\\Setup\\VC'
    vs_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vs_key, 'ProductDir')
    vc_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, vc_key, 'ProductDir')
    
    # On a 64-bit host, look for a 32-bit installation 

    if (not vs_dir or not vc_dir):
        vs_key = 'SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\' + \
            vs_ver + '\\Setup\\VS'
        vc_key = 'SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\' + \
            vs_ver + '\\Setup\\VC'
        vs_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, 
                                vs_key, 'ProductDir')
        vc_dir = _read_registry(winreg.HKEY_LOCAL_MACHINE, 
                                vc_key, 'ProductDir')
    return (vs_dir,vc_dir) 
Example #10
Source File: local.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def is_installed(self):
        # Bethesda client is not available for macOs
        if sys.platform != 'win32':
            log.info("Platform is not compatible")
            return False
        path = None
        try:
            log.info("Connecting to hkey_local_machine key")
            reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
            log.info(f"Opening key at {reg}, {BETTY_WINREG_LOCATION}")
            with winreg.OpenKey(reg, BETTY_WINREG_LOCATION) as key:
                path = winreg.QueryValueEx(key, "installLocation")[0]
            log.info(f"Checking if path exists at {os.path.join(path, BETTY_LAUNCHER_EXE)}")
            self.betty_client_path = path
            return os.path.exists(os.path.join(path, BETTY_LAUNCHER_EXE))
        except (OSError, KeyError):
            self.betty_client_path = path
            return False
        except Exception as e:
            self.betty_client_path = path
            log.exception(f"Exception while checking if client is installed, assuming not installed {repr(e)}")
            return False 
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: twitch_launcher_client.py    From galaxy-plugin-twitch with GNU General Public License v3.0 6 votes vote down vote up
def _get_launcher_install_path(self) -> Optional[str]:
        if is_windows():

            try:
                for h_root in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
                    with winreg.OpenKey(h_root, r"Software\Microsoft\Windows\CurrentVersion\Uninstall") as h_apps:
                        for idx in range(winreg.QueryInfoKey(h_apps)[0]):
                            try:
                                with winreg.OpenKeyEx(h_apps, winreg.EnumKey(h_apps, idx)) as h_app_info:
                                    def get_value(key):
                                        return winreg.QueryValueEx(h_app_info, key)[0]

                                    if get_value("DisplayName") == self._LAUNCHER_DISPLAY_NAME:
                                        installer_path = get_value("InstallLocation")
                                        if os.path.exists(str(installer_path)):
                                            return installer_path

                            except (WindowsError, KeyError, ValueError):
                                continue

            except (WindowsError, KeyError, ValueError):
                logging.exception("Failed to get client install location")
                return None
        else:
            return None 
Example #13
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 #14
Source File: reader.py    From pypykatz with MIT License 5 votes vote down vote up
def get_class(self, key_path, throw = True):
		if self.root is None:
			self.setup()
			
		pkey = winreg.HKEY_LOCAL_MACHINE
		key_path = self.hive_name + '\\' + key_path
		for name in key_path.split('\\'):
			pkey = RegOpenKey(pkey, name)
	
		ki = RegQueryInfoKey(pkey)		
		return ki[0].decode() 
Example #15
Source File: reader.py    From pypykatz with MIT License 5 votes vote down vote up
def __init__(self, hive_name, root = winreg.HKEY_LOCAL_MACHINE):
		self.hive_name = hive_name
		self.root = root 
Example #16
Source File: _msvccompiler.py    From setuptools with MIT License 5 votes vote down vote up
def _find_vc2015():
    try:
        key = winreg.OpenKeyEx(
            winreg.HKEY_LOCAL_MACHINE,
            r"Software\Microsoft\VisualStudio\SxS\VC7",
            access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY
        )
    except OSError:
        log.debug("Visual C++ is not registered")
        return None, None

    best_version = 0
    best_dir = None
    with key:
        for i in count():
            try:
                v, vc_dir, vt = winreg.EnumValue(key, i)
            except OSError:
                break
            if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
                try:
                    version = int(float(v))
                except (ValueError, TypeError):
                    continue
                if version >= 14 and version > best_version:
                    best_version, best_dir = version, vc_dir
    return best_version, best_dir 
Example #17
Source File: tzwin.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, name):
        self._name = name

        handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
        tzkey = winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name))
        keydict = valuestodict(tzkey)
        tzkey.Close()
        handle.Close()

        self._stdname = keydict["Std"].encode("iso-8859-1")
        self._dstname = keydict["Dlt"].encode("iso-8859-1")

        self._display = keydict["Display"]
        
        # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
        tup = struct.unpack("=3l16h", keydict["TZI"])
        self._stdoffset = -tup[0]-tup[1]         # Bias + StandardBias * -1
        self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1
        
        (self._stdmonth,
         self._stddayofweek,  # Sunday = 0
         self._stdweeknumber, # Last = 5
         self._stdhour,
         self._stdminute) = tup[4:9]

        (self._dstmonth,
         self._dstdayofweek,  # Sunday = 0
         self._dstweeknumber, # Last = 5
         self._dsthour,
         self._dstminute) = tup[12:17] 
Example #18
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 #19
Source File: tzwin.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self):

        handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

        tzlocalkey = winreg.OpenKey(handle, TZLOCALKEYNAME)
        keydict = valuestodict(tzlocalkey)
        tzlocalkey.Close()

        self._stdname = keydict["StandardName"].encode("iso-8859-1")
        self._dstname = keydict["DaylightName"].encode("iso-8859-1")

        try:
            tzkey = winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname))
            _keydict = valuestodict(tzkey)
            self._display = _keydict["Display"]
            tzkey.Close()
        except OSError:
            self._display = None

        handle.Close()
        
        self._stdoffset = -keydict["Bias"]-keydict["StandardBias"]
        self._dstoffset = self._stdoffset-keydict["DaylightBias"]


        # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
        tup = struct.unpack("=8h", keydict["StandardStart"])

        (self._stdmonth,
         self._stddayofweek,  # Sunday = 0
         self._stdweeknumber, # Last = 5
         self._stdhour,
         self._stdminute) = tup[1:6]

        tup = struct.unpack("=8h", keydict["DaylightStart"])

        (self._dstmonth,
         self._dstdayofweek,  # Sunday = 0
         self._dstweeknumber, # Last = 5
         self._dsthour,
         self._dstminute) = tup[1:6] 
Example #20
Source File: tzwin.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def __init__(self):

        handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

        tzlocalkey = winreg.OpenKey(handle, TZLOCALKEYNAME)
        keydict = valuestodict(tzlocalkey)
        tzlocalkey.Close()

        self._stdname = keydict["StandardName"].encode("iso-8859-1")
        self._dstname = keydict["DaylightName"].encode("iso-8859-1")

        try:
            tzkey = winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname))
            _keydict = valuestodict(tzkey)
            self._display = _keydict["Display"]
            tzkey.Close()
        except OSError:
            self._display = None

        handle.Close()
        
        self._stdoffset = -keydict["Bias"]-keydict["StandardBias"]
        self._dstoffset = self._stdoffset-keydict["DaylightBias"]


        # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
        tup = struct.unpack("=8h", keydict["StandardStart"])

        (self._stdmonth,
         self._stddayofweek,  # Sunday = 0
         self._stdweeknumber, # Last = 5
         self._stdhour,
         self._stdminute) = tup[1:6]

        tup = struct.unpack("=8h", keydict["DaylightStart"])

        (self._dstmonth,
         self._dstdayofweek,  # Sunday = 0
         self._dstweeknumber, # Last = 5
         self._dsthour,
         self._dstminute) = tup[1:6] 
Example #21
Source File: windows.py    From start_jupyter_cm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _remove_jupyter_here(all_users):
    if all_users:
        h_key_base = winreg.HKEY_LOCAL_MACHINE
        install_type = "all users"
    else:
        h_key_base = winreg.HKEY_CURRENT_USER
        install_type = "single user"

    for terminal in ('qtconsole', 'notebook', 'lab'):
        try:
            winreg.DeleteKey(
                h_key_base,
                r'Software\Classes\Directory\shell\jupyter_%s_here%s\Command' % (
                terminal, CONDA_ENV_LABEL.replace(" ", "_")))
            winreg.DeleteKey(
                h_key_base,
                r'Software\Classes\Directory\shell\jupyter_%s_here%s' % (
                terminal, CONDA_ENV_LABEL.replace(" ", "_")))
            winreg.DeleteKey(
                h_key_base,
                r'Software\Classes\Directory\Background\shell\jupyter_%s_here%s\Command' % (
                terminal, CONDA_ENV_LABEL.replace(" ", "_")))
            winreg.DeleteKey(
                h_key_base,
                r'Software\Classes\Directory\Background\shell\jupyter_%s_here%s' % (
                terminal, CONDA_ENV_LABEL.replace(" ", "_")))
            print("Jupyter %s here%s context menu entry removed for %s." % (
                    terminal, CONDA_ENV_LABEL, install_type))
        except FileNotFoundError:
            # If this fails it is because it was not installed, so nothing to
            # worry about.
            pass 
Example #22
Source File: tzwin.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def __init__(self, name):
        self._name = name

        handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
        tzkey = winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name))
        keydict = valuestodict(tzkey)
        tzkey.Close()
        handle.Close()

        self._stdname = keydict["Std"].encode("iso-8859-1")
        self._dstname = keydict["Dlt"].encode("iso-8859-1")

        self._display = keydict["Display"]
        
        # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
        tup = struct.unpack("=3l16h", keydict["TZI"])
        self._stdoffset = -tup[0]-tup[1]         # Bias + StandardBias * -1
        self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1
        
        (self._stdmonth,
         self._stddayofweek,  # Sunday = 0
         self._stdweeknumber, # Last = 5
         self._stdhour,
         self._stdminute) = tup[4:9]

        (self._dstmonth,
         self._dstdayofweek,  # Sunday = 0
         self._dstweeknumber, # Last = 5
         self._dsthour,
         self._dstminute) = tup[12:17] 
Example #23
Source File: tzwin.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def list():
        """Return a list of all time zones known to the system."""
        handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
        tzkey = winreg.OpenKey(handle, TZKEYNAME)
        result = [winreg.EnumKey(tzkey, i)
                  for i in range(winreg.QueryInfoKey(tzkey)[0])]
        tzkey.Close()
        handle.Close()
        return result 
Example #24
Source File: tzwin.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def _settzkeyname():
    global TZKEYNAME
    handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    try:
        winreg.OpenKey(handle, TZKEYNAMENT).Close()
        TZKEYNAME = TZKEYNAMENT
    except WindowsError:
        TZKEYNAME = TZKEYNAME9X
    handle.Close() 
Example #25
Source File: recipe-577621.py    From code with MIT License 5 votes vote down vote up
def __init__(self, scope):
        assert scope in ('user', 'system')
        self.scope = scope
        if scope == 'user':
            self.root = winreg.HKEY_CURRENT_USER
            self.subkey = 'Environment'
        else:
            self.root = winreg.HKEY_LOCAL_MACHINE
            self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' 
Example #26
Source File: get_applications.py    From BoomER with GNU General Public License v3.0 5 votes vote down vote up
def search_register(self, option_hk, key_path):
        if option_hk == 0:
            h_key = winreg.HKEY_CURRENT_USER
            data = "HKEY_CURRENT_USER -> "
        else:
            h_key = winreg.HKEY_LOCAL_MACHINE
            data = "HKEY_LOCAL_MACHINE -> "
        self.print_info(data + key_path)
        if self.file_open:
            self.file_open.write("\n" + data + key_path + "\n\n")
        key = winreg.OpenKey(h_key, key_path, 0, winreg.KEY_READ)
        for subkey in self.get_subkeys(key):
            subkey_path = "%s\\%s" % (key_path, subkey)
            self.get_apps_values(h_key, subkey_path)
        winreg.CloseKey(key) 
Example #27
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 
Example #28
Source File: mapiex.py    From nsf2x with GNU General Public License v2.0 5 votes vote down vote up
def MimeToMapi (self, eml, m, flag = 0) :
        if self.converter == None :
            clsid = win32com.mapi.mapi.CLSID_IConverterSession
            iid = win32com.mapi.mapi.IID_IConverterSession
                        
            try:
                tmp = pythoncom.CoCreateInstance (clsid, None, pythoncom.CLSCTX_INPROC_SERVER, pythoncom.IID_IUnknown)
                self.converter = tmp.QueryInterface (iid)
                
            except :
                # Test for ClickToRun version of Outlook and manually load library and create instance
                for iconvpath in ("", "16.0", "15.0") :
                    regpath =  os.path.join ("Software","Microsoft","Office",iconvpath,"ClickToRun","Registry","Machine","Software","Classes")                     
                    if platform.machine() == "AMD64" and platform.architecture()[0] == "32bit":
                        # 32bit application on 64bit platform
                        regpath = os.path.join (regpath,"Wow6432Node")
                    regpath = os.path.join (regpath,"CLSID", str(clsid),"InprocServer32")
                
                    self.converter = self.CoCreateInstanceC2R (winreg.HKEY_LOCAL_MACHINE, regpath, clsid, iid)
                    if self.converter != None :
                        break
                
                if self.converter == None :
                     NameError("mapi:MimeToMapi : Can not create IConverterSession instance")
                            
        # Open file as IStream. Don't use win32com.mapi.mapi.OpenStreamOnFile as it doesn't
        # handle Unicode file names
        f = open(eml, "rb")
        Istrm = util.wrap (FileStream(f), pythoncom.IID_IUnknown, None, True)

        self.converter.MIMEToMAPI(Istrm, m, flag) 
Example #29
Source File: configuration.py    From RWMS with GNU General Public License v2.0 5 votes vote down vote up
def detect_steam():
    """
    automatic detection of steam
    :return: path to steam base directory
    """
    disablesteam = load_value("rwms", "disablesteam", True)
    if disablesteam:
        return ""
    steampath = load_value("paths", "steamdir")
    key = None
    if steampath == "":
        if sys.platform == "win32":
            registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
            if registry:
                try:
                    key = winreg.OpenKey(registry, r"SOFTWARE\WoW6432Node\Valve\Steam")
                except:
                    steampath = ""
                if key:
                    steampath, _ = winreg.QueryValueEx(key, "InstallPath")
            winreg.CloseKey(registry)
        elif sys.platform == "darwin":
            steampath = os.environ["HOME"] + "/Library/Application Support/Steam"
        elif sys.platform == "linux":
            steampath = os.environ["HOME"] + "/.steam/steam"
    return steampath 
Example #30
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 ('', '')