def __init__(self): if "Win" not in platform.system(): raise CannotInvoke, "Winamp only available on Windows systems" self.play_command = None self.enqueue_command = None import _winreg openkeys = [] try: try: key = _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, r'Winamp.File\shell\open\command', 0, _winreg.KEY_QUERY_VALUE) openkeys.insert(0, key) self.play_command, type = _winreg.QueryValueEx(key, "") key = _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, r'Winamp.File\shell\Enqueue\command', 0, _winreg.KEY_QUERY_VALUE) openkeys.insert(0, key) self.enqueue_command, type = _winreg.QueryValueEx(key, "") finally: for key in openkeys: _winreg.CloseKey(key) except WindowsError, e: errno, message = e.args if errno != 2: raise e
def get_device_list(self): try: base_key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, self._PASSTHRU_REG) count = _winreg.QueryInfoKey(base_key)[0] if count == 0: return False J2534_Device_Reg_Info = [] for i in range(count): DeviceKey = _winreg.OpenKeyEx(base_key, _winreg.EnumKey(base_key, i)) Name = _winreg.QueryValueEx(DeviceKey, 'Name')[0] FunctionLibrary = _winreg.QueryValueEx(DeviceKey, 'FunctionLibrary')[0] J2534_Device_Reg_Info.append((Name, FunctionLibrary)) return J2534_Device_Reg_Info except WindowsError as e: return False
def _windows_registry_get_adopt_open_jdk_8_path(): try: import _winreg except ImportError: import winreg as _winreg try: # The registry key name looks like: # HKLM\SOFTWARE\AdoptOpenJDK\JDK\8.0.252.09\hotspot\MSI:Path # ^^^^^^^^^^ # Due to the very precise version in the path, we can't just OpenKey("<static path>"). # Instead, we need to enumerate the list of JDKs, find the one that seems to be what # we're looking for (JDK 1.8), then get the path from there. with _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\AdoptOpenJDK\JDK") as jdk_key: index = 0 while True: version_key_name = _winreg.EnumKey(jdk_key, index) if not version_key_name.startswith("8."): index += 1 continue with _winreg.OpenKeyEx( jdk_key, r"{}\hotspot\MSI".format(version_key_name)) as msi_key: path, _ = _winreg.QueryValueEx(msi_key, "Path") return os.path.join(path, "bin") except (FileNotFoundError, OSError): return None
def getDevices(): """TODO: 获取更多key,比如支持测protocols; """ BaseKey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, PASSTHRU_REG) count = winreg.QueryInfoKey(BaseKey)[0] J2534_Device_Reg_Info = dict() for i in range(count): DeviceKey = winreg.OpenKeyEx(BaseKey, winreg.EnumKey(BaseKey, i)) singleDll = dict() singleDll['Name'] = winreg.QueryValueEx(DeviceKey, 'Name')[0] singleDll['FunctionLibrary'] = winreg.QueryValueEx( DeviceKey, 'FunctionLibrary')[0] J2534_Device_Reg_Info[i] = singleDll return J2534_Device_Reg_Info
def set_windows_path(self, cocos_consle_root): import _winreg try: env = None path = None env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, 'Environment', 0, _winreg.KEY_SET_VALUE | _winreg.KEY_READ) path = _winreg.QueryValueEx(env, 'Path')[0] path = path + ';' + cocos_consle_root path.replace('/', '\\') _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path) _winreg.FlushKey(env) _winreg.CloseKey(env) except Exception: if not path: path = cocos_consle_root.replace('/', '\\') _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path) _winreg.FlushKey(env) else: _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path) _winreg.FlushKey(env) if env: _winreg.CloseKey(env) return False return True
def GetEnv(self, key): value = None try: value = os.environ[key] except Exception: if self.platform == self.platforms.windows: import _winreg try: env = None env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_SET_VALUE|_winreg.KEY_READ) value = _winreg.QueryValueEx(env, key)[0] except Exception: pass finally: if env is not None: _winreg.CloseKey(env) elif (self.platform == self.platforms.linux or self.platform == self.platforms.mac): if self.file is not None: try: file = None file = open(self.file) import re self.patten = re.compile(r"^export[ \t]+%s=(.+)"%key) for line in file: match = self.patten.match(line.lstrip(" \t")) if match is not None: value = match.group(1) break except Exception: pass finally: if file is not None: file.close() return value
def openProjectPath(self, project_path): print project_path self.project_path = project_path projectFile = open(project_path, "r") projectJson = json.load(projectFile) projectFile.close() # Fill up attributes self.unreal_version = projectJson["EngineAssociation"] if "Version" in projectJson: self.version = projectJson["Version"] # Check Engine Association if self.unreal_version.startswith("4."): regHandle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = _winreg.OpenKeyEx( regHandle, "SOFTWARE\\EpicGames\\Unreal Engine\\%s" % self.unreal_version, 0, (_winreg.KEY_WOW64_64KEY | _winreg.KEY_READ)) if key: self.unreal_path = _winreg.QueryValueEx( key, "InstalledDirectory")[0] self.unreal_path = self.unreal_path.replace("/", "\\") else: regHandle = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) key = _winreg.OpenKey( regHandle, r"Software\\Epic Games\\Unreal Engine\\Builds") if key: self.unreal_path = _winreg.QueryValueEx( key, self.unreal_version)[0] self.unreal_path = self.unreal_path.replace("/", "\\")
def regOpenKey(root, key, sam=_winreg.KEY_READ): if not key: return None try: return _winreg.OpenKeyEx(root, key, 0, sam) except WindowsError: return None
def cookie_dir(self): import _winreg as winreg key = winreg.OpenKeyEx( winreg.HKEY_CURRENT_USER, 'Software' r'\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') cookie_dir, type = winreg.QueryValueEx(key, 'Cookies') return cookie_dir
def get_saved_password(name): r"""Retrieve previously saved password. The password is returned unencrypted. *name* is used to lookup a password on this machine, which must be the same *name* used in :py:func:`.save_password`.""" try: # Only import pywin32 dependency if user creates a project # that requires encrypted password. import win32crypt except ImportError: raise DistutilsModuleError("system missing required win32api " "module. You can download from " "http://sourceforge.net/projects.pywin32") try: # retrieve value from user's private registry with _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "SOFTWARE\\signet") as key: enc = _winreg.QueryValue(key, name) enc = base64.b64decode(enc) # decrypt password using DPAPI (CRYPTPROECT_LOCAL_MACHINE) return win32crypt.CryptUnprotectData(enc, None, None, None, 4)[1] except (WindowsError, IndexError): return None
def GetLocalTimeZone(): """Returns the local time zone as defined by the operating system in the registry. Note that this will only work if the TimeZone in the registry has not been customized. It should have been selected from the Windows interface. >>> localTZ = GetLocalTimeZone() >>> nowLoc = datetime.datetime.now( localTZ ) >>> nowUTC = datetime.datetime.utcnow( ) >>> ( nowUTC - nowLoc ) < datetime.timedelta( seconds = 5 ) Traceback (most recent call last): ... TypeError: can't subtract offset-naive and offset-aware datetimes >>> nowUTC = nowUTC.replace( tzinfo = TimeZoneInfo( 'GMT Standard Time', True ) ) Now one can compare the results of the two offset aware values >>> ( nowUTC - nowLoc ) < datetime.timedelta( seconds = 5 ) True """ tzRegKey = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, tzRegKey) local = _RegKeyDict(key) # if the user has not checked "Automatically adjust clock for daylight # saving changes" in the Date and Time Properties control, the standard # and daylight values will be the same. If this is the case, create a # timezone object fixed to standard time. fixStandardTime = local['StandardName'] == local['DaylightName'] and \ local['StandardBias'] == local['DaylightBias'] return TimeZoneInfo(local['StandardName'], fixStandardTime)
def remove_dir_from_win_path(self, remove_dir): import _winreg try: env = None path = None env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, 'Environment', 0, _winreg.KEY_SET_VALUE | _winreg.KEY_READ) path = _winreg.QueryValueEx(env, 'Path')[0] path_lower = path.lower() remove_dir = remove_dir.replace('/', '\\') remove_dir_lower = remove_dir.lower() start_pos = path_lower.find(remove_dir_lower) if (start_pos >= 0): length = len(remove_dir_lower) need_remove = path[start_pos:(start_pos + length)] path = path.replace(need_remove, '') path = path.replace(';;', ';') _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path) _winreg.FlushKey(env) _winreg.CloseKey(env) print(' ->Remove directory \"%s\" from PATH!\n' % remove_dir) except Exception: print(' ->Remove directory \"%s\" from PATH failed!\n' % remove_dir)
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
def phkey(self): if self._phkey is not None: return self._phkey try: self._phkey = _winreg.OpenKeyEx(self.surkey.phkey, self.name, 0, self.sam) except WindowsError as e: raise WindowsError("Could not open registry key <{0}>".format(self.fullname)) return self._phkey
def GetIndexedTimeZoneNames(index_key='Index'): """Returns the names of the time zones as defined in the registry, but includes an index by which they may be sorted. Default index is "Index" by which they may be sorted longitudinally.""" for timeZoneName in GetTimeZoneNames(): tzRegKeyPath = os.path.join(TimeZoneInfo.tzRegKey, timeZoneName) key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, tzRegKeyPath) tzIndex, type = _winreg.QueryValueEx(key, index_key) yield (tzIndex, timeZoneName)
def reg_value(value_name): # Yes I know that win32api includes Reg* functions, # but KEY_WOW64_64KEY flag to access 64bit registry from 32bit app doesn't works hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, REG_KEY, 0, winreg.KEY_READ) try: return winreg.QueryValueEx(hkey, value_name)[0] finally: winreg.CloseKey(hkey)
def delete_registry_entries(self): ''' @summary: Deletes the timer registry key ''' # Open and delete the key reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) _winreg.DeleteKeyEx(reg, "") _winreg.CloseKey(reg)
def sid2user(sid): try: keyname = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{0}'.format( sid) key = wr.OpenKeyEx(wr.HKEY_LOCAL_MACHINE, keyname) value, _ = wr.QueryValueEx(key, 'ProfileImagePath') user = value.split('\\')[-1] return user except: return sid
def get_cpu_info(): reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor") flag = True model_name = "" num = _winreg.QueryInfoKey(reg)[0] reg2 = _winreg.OpenKeyEx(reg, _winreg.EnumKey(reg, 0)) model_name = _winreg.QueryValueEx(reg2, 'ProcessorNameString')[0] return "{} *{}".format(model_name, num)
def open(self, keyhandle, keypath, flags=None): if type(keypath) is str: keypath = keypath.split('\\') if flags is None: for subkey in keypath: keyhandle = _winreg.CreateKey(keyhandle, subkey) else: for subkey in keypath: keyhandle = _winreg.OpenKeyEx(keyhandle, subkey, 0, flags) self.keyhandle = keyhandle
def findGuid(self, guid): s = self.guidStr(guid) if s.upper() in self.manual: return {"guid": s, "name": self.manual[s.upper()].encode('ascii'), "prefix": None} reg = { _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, "Interface", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY): "IID", _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, "CLSID", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY): "CLSID", _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, "Interface", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_32KEY): "IID", _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT, "CLSID", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_32KEY): "CLSID", } for y in reg: try: k = _winreg.OpenKey(y, s) nm = _winreg.QueryValue(k, None) if nm: return {"guid": s, "name": nm, "prefix": reg[y]} except Exception: continue return None
def runVS(self): # See https://pascoal.net/2011/04/29/getting-visual-studio-installation-directory/ regHandle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = _winreg.OpenKeyEx(regHandle, "SOFTWARE\\Microsoft\\VisualStudio\\14.0") if key: visualStudioPath = _winreg.QueryValueEx(key, "InstallDir")[0] prog = visualStudioPath + "devenv.exe" commands = [prog, self.project_path.replace(".uproject", ".sln")] subprocess.Popen(commands, shell=False)
def exists(self): # Best way todo ? # TODO: document if self._phkey is not None: return True try: tmpphkey = _winreg.OpenKeyEx(self.surkey.phkey, self.name) except WindowsError as e: return False _winreg.CloseKey(tmpphkey) return True
def __remove_from_startup_programs(self): ''' @summary: Removes Crypter from the list of startup programs @todo: Code and test ''' try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION, 0, _winreg.KEY_SET_VALUE) _winreg.DeleteValue(reg, "Crypter") _winreg.CloseKey(reg) except WindowsError: pass
def read_value(key, root=_winreg.HKEY_LOCAL_MACHINE): base = os.path.dirname(key) val = os.path.basename(key) try: handle = _winreg.OpenKeyEx(root, base) try: value, type = _winreg.QueryValueEx(handle, val) return value finally: _winreg.CloseKey(handle) except _winreg.error: return None
def delete_registry_entries(self): ''' @summary: Deletes the timer registry key ''' # Open and delete the key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) _winreg.DeleteKeyEx(reg, "") _winreg.CloseKey(reg) except WindowsError: # Ignore any Windows errors pass
def isWinNT(self): """Are we running in Windows NT?""" if self.getType() == 'win32': import _winreg try: k=_winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion') _winreg.QueryValueEx(k, 'SystemRoot') return 1 except WindowsError: return 0 # not windows NT return 0
def get_winsdk_path(): r"""Retrieve installed path for windows sdk.""" key = None try: with _winreg.OpenKeyEx( _winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows") as key: pth = _winreg.QueryValueEx(key, 'CurrentInstallFolder')[0] return re.sub(r'\\\\', r'\\', pth) except (WindowsError, IndexError): raise RuntimeError('missing windows sdk registry entry: %s' % WINSDK_ERROR)
def get_oracle_jdk_8_path(): try: import _winreg except ImportError: import winreg as _winreg try: with _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\JavaSoft\Java Development Kit\1.8') as key: path, _ = _winreg.QueryValueEx(key, 'JavaHome') return path except FileNotFoundError: return None
def _FindTimeZoneKey(self): """Find the registry key for the time zone name (self.timeZoneName).""" # for multi-language compatability, match the time zone name in the # "Std" key of the time zone key. zoneNames = dict(GetIndexedTimeZoneNames('Std')) # Also match the time zone key name itself, to be compatible with # English-based hard-coded time zones. timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName) tzRegKeyPath = os.path.join(self.tzRegKey, timeZoneName) try: key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, tzRegKeyPath) except: raise ValueError, 'Timezone Name %s not found.' % timeZoneName return key