我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用winreg.CloseKey()。
def __init__(self, **kwargs): python_version = kwargs.pop('python', '3.4') python_path = None for node in ('Wow6432Node\\', ''): try: key = compat_winreg.OpenKey( compat_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\%sPython\PythonCore\%s\InstallPath' % (node, python_version)) try: python_path, _ = compat_winreg.QueryValueEx(key, '') finally: compat_winreg.CloseKey(key) break except Exception: pass if not python_path: raise BuildError('No such Python version: %s' % python_version) self.pythonPath = python_path super(PythonBuilder, self).__init__(**kwargs)
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)
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)
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
def _delete_key_if_empty(self, service): key_name = r'Software\%s\Keyring' % 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
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
def addActionToShell(self, name, descr, cmd): """ add action in windows explorer on top of file & dir """ if descr == "": descr = name import winreg as winreg for item in ["*", "Directory"]: key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'%s\shell\%s' % (item, name)) key2 = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'%s\shell\%s\Command' % (item, name)) winreg.SetValueEx(key, "", None, winreg.REG_SZ, "%s " % descr) winreg.SetValueEx(key, "Icon", None, winreg.REG_SZ, "") winreg.SetValueEx(key, "Position", None, winreg.REG_SZ, "Top") winreg.SetValueEx(key, "", None, winreg.REG_SZ, "%s " % descr) #winreg.SetValueEx(key2,"",None,winreg.REG_SZ,r'cmd.exe /s /k pushd "%V"') winreg.SetValueEx(key2, "", None, winreg.REG_SZ, cmd) winreg.CloseKey(key)
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)
def getenv(self, name): key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ) try: value, _ = winreg.QueryValueEx(key, name) except WindowsError: value = '' winreg.CloseKey(key) return value
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)
def _reg_query_sub_keys(handle, key, keylist = []): reghandle = reg.OpenKey(handle, key, 0, reg.KEY_READ) try: i = 0 while True: subkey = reg.EnumKey(reghandle, i) i += 1 _reg_query_sub_keys(handle, key + subkey + "\\", keylist) except WindowsError as ex: if ex.winerror == 259: keylist.append(key) finally: reg.CloseKey(reghandle)
def cal_share_path(): global share_path if os.path.isfile("configure.ac"): share_path=os.getcwd() return if os.path.isfile("ver.py"): share_path=os.path.abspath(os.path.join(os.getcwd(), os.pardir)) return if running_on_linux()==False: try: registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\gpvdm", 0, winreg.KEY_READ) value, regtype = winreg.QueryValueEx(registry_key, "installpath") winreg.CloseKey(registry_key) share_path=value except WindowsError: if os.path.isfile(os.path.join(os.getcwd(),"gpvdm_core.exe")): share_path=os.getcwd() else: share_path="c:\\gpvdm" print("No registry key found using default",share_path) else: if os.path.isdir("/usr/lib64/gpvdm"): share_path="/usr/lib64/gpvdm/" elif os.path.isdir("/usr/lib/gpvdm"): share_path="/usr/lib/gpvdm/" else: share_path=os.path.dirname(os.path.dirname(os.path.realpath(__file__))) print("I don't know where the shared files are assuming ",share_path)
def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") except WindowsError: # No registered Python installations return {} i = 0 versions = [] while True: try: versions.append(winreg.EnumKey(python_core, i)) i = i + 1 except WindowsError: break exes = dict() for ver in versions: try: path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver) except WindowsError: continue exes[ver] = join(path, "python.exe") winreg.CloseKey(python_core) # Add the major versions # Sort the keys, then repeatedly update the major version entry # Last executable (i.e., highest version) wins with this approach for ver in sorted(exes): exes[ver[0]] = exes[ver] return exes
def _del_hkey(self): if self.parent is not None: try: _winreg.CloseKey(self.__dict__["hkey"]) except KeyError: pass try: del self.__dict__["hkey"] except KeyError: pass
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
def setEnvironment(scope, name, value): assert scope in ('user', 'system') #INFO_MSG('set environment: name=%s, value=%s' % (name, value)) if platform.system() == 'Windows': root, subkey = getWindowsEnvironmentKey(scope) # Note: for 'system' scope, you must run this as Administrator key = winreg.OpenKey(root, subkey, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value) winreg.CloseKey(key) else: if name.lower() == 'uid': uid, username = value if uid != str(os.geteuid()): ret, cret = syscommand('bash -c \'usermod -d /home/%s/ -u %s %s\'' % (pwd.getpwnam(username).pw_dir, uid, username), True) INFO_MSG(ret) INFO_MSG(cret) return userhome = "~" if len(os_user_name) > 0: userhome = pwd.getpwnam(os_user_name).pw_dir f = open('%s/.bashrc' % userhome, 'a') f.write("export %s=%s\n\n" % (name, value)) f.close() if os.geteuid() > 0: syscommand('bash -c \'source %s/.bashrc\'' % userhome, False)
def on_quit(systray): stop_GotoX() winreg.CloseKey(SETTINGS) global running running = False
def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = r'Software\%s\Keyring' % service hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) winreg.DeleteValue(hkey, username) winreg.CloseKey(hkey) except WindowsError: e = sys.exc_info()[1] raise PasswordDeleteError(e) self._delete_key_if_empty(service)
def checkstartup(): # check if it is linux if os_type == "Linux" or os_type == "FreeBSD" or os_type == 'OpenBSD': # check if the startup exists if os.path.exists(home_address + "/.config/autostart/persepolis.desktop"): return True else: return False # check if it is mac elif os_type == "Darwin": # OS X if os.path.exists(home_address + "/Library/LaunchAgents/com.persepolisdm.plist"): return True else: return False # check if it is Windows elif os_type == "Windows": # try to open startup key and check persepolis value try: aKey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_ALL_ACCESS) startupvalue = winreg.QueryValueEx(aKey, 'persepolis') startup = True except WindowsError: startup = False # Close the connection winreg.CloseKey(aKey) # if the startup enabled or disabled if startup: return True if not startup: return False # add startup file
def removestartup(): # check if it is linux if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD': # remove it os.remove(home_address + "/.config/autostart/persepolis.desktop") # check if it is mac OS elif os_type == "Darwin": # OS X if checkstartup(): os.system('launchctl unload ' + home_address + "/Library/LaunchAgents/com.persepolisdm.plist") os.remove(home_address + "/Library/LaunchAgents/com.persepolisdm.plist") # check if it is Windows elif os_type == 'Windows': if checkstartup(): # Connect to the startup path in Registry key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_ALL_ACCESS) # remove persepolis from startup winreg.DeleteValue(key, 'persepolis') # Close connection winreg.CloseKey(key)
def _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PUTTY_is1", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\FileZilla Client", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def _autodetect_official_installreg(self): try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) value = winreg.QueryValueEx(key, "InstallLocation")[0] winreg.CloseKey(key) exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL) if os.path.exists(exe_file): return exe_file except: pass return None
def add(name, application): """add a new autostart entry""" key = get_runonce() try: winreg.SetValueEx(key, name, 0, winreg.REG_SZ, application) except WindowsError as e: print(e) winreg.CloseKey(key)
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
def remove(name): """delete an autostart entry""" if exists("BingNiceWallpapers"): key = get_runonce() winreg.DeleteValue(key, name) winreg.CloseKey(key)
def remove_from_system_path(pathname, allusers=True, path_env_var='PATH'): """Removes all entries from the path which match the value in 'pathname' You must call broadcast_environment_settings_change() after you are finished manipulating the environment with this and other functions. For example, # Remove Anaconda from PATH remove_from_system_path(r'C:\Anaconda') broadcast_environment_settings_change() """ pathname = path.normcase(path.normpath(pathname)) envkeys = [(reg.HKEY_CURRENT_USER, r'Environment')] if allusers: envkeys.append((reg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')) for root, keyname in envkeys: key = reg.OpenKey(root, keyname, 0, reg.KEY_QUERY_VALUE|reg.KEY_SET_VALUE) reg_value = None try: reg_value = reg.QueryValueEx(key, path_env_var) except WindowsError: # This will happen if we're a non-admin install and the user has # no PATH variable. reg.CloseKey(key) continue try: any_change = False results = [] for v in reg_value[0].split(os.pathsep): vexp = sz_expand(v, reg_value[1]) # Check if the expanded path matches the # requested path in a normalized way if path.normcase(path.normpath(vexp)) == pathname: any_change = True else: # Append the original unexpanded version to the results results.append(v) modified_path = os.pathsep.join(results) if any_change: reg.SetValueEx(key, path_env_var, 0, reg_value[1], modified_path) except: # If there's an error (e.g. when there is no PATH for the current # user), continue on to try the next root/keyname pair reg.CloseKey(key)
def _detect_distro_official(self, given_enabled, given_label, given_path): dist_props = { 'enabled': given_enabled, 'label': given_label, 'exe_file': None, 'cmd_args': ['-load', '%1'], 'sessions': []} # label if not dist_props['label']: dist_props['label'] = "PuTTY" # enabled? don't go further if not if dist_props['enabled'] is None: dist_props['enabled'] = True if not dist_props['enabled']: return dist_props # find executable exe_file = None if given_path: exe_file = os.path.normpath(os.path.join(given_path, self.EXE_NAME_OFFICIAL)) if not os.path.exists(exe_file): exe_file = None if not exe_file: exe_file = self._autodetect_official_installreg() if not exe_file: exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "PuTTY.lnk") if not exe_file: exe_file = self._autodetect_official_progfiles() if not exe_file: exe_file = self._autodetect_path(self.EXE_NAME_OFFICIAL) #if not exe_file: # exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "*putty*.lnk") if not exe_file: return None dist_props['exe_file'] = exe_file # list configured sessions try: hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, 'Software\\SimonTatham\\PuTTY\\Sessions') index = 0 while True: try: dist_props['sessions'].append(urllib.parse.unquote( winreg.EnumKey(hkey, index), encoding='mbcs')) index += 1 except OSError: break winreg.CloseKey(hkey) except OSError: pass return dist_props
def _list_item_info(self, clsid, reg_clsid): def _getregstr(hkey, sub_path, value_name): try: if sub_path is not None: hkey_sub = winreg.OpenKey(hkey, sub_path) else: hkey_sub = hkey (val, typ) = winreg.QueryValueEx(hkey_sub, value_name) if sub_path is not None: winreg.CloseKey(hkey_sub) if isinstance(val, str) and len(val) > 0: return val except OSError: pass return None cpitem = { 'clsid': clsid, 'canonical_name': _getregstr(reg_clsid, None, "System.ApplicationName"), 'open_command': _getregstr(reg_clsid, "Shell\\Open\\Command", None), 'label': None, 'short_desc': None, 'icon_location': _getregstr(reg_clsid, "DefaultIcon", None), 'icon_handle': None} # skip item if it doesn't have a canonical name or a command to execute if not cpitem['canonical_name'] and not cpitem['open_command']: return None # label location = _getregstr(reg_clsid, None, "LocalizedString") if location is not None: cpitem['label'] = kpu.shell_string_resource(location) if cpitem['label'] is None: cpitem['label'] = _getregstr(reg_clsid, None, None) # skip item if it doesn't have a label if not cpitem['label']: return None # short_desc location = _getregstr(reg_clsid, None, "InfoTip") if location is not None: cpitem['short_desc'] = kpu.shell_string_resource(location) if cpitem['short_desc'] is None: cpitem['short_desc'] = "" # icon if cpitem['icon_location'] is not None: if cpitem['icon_location'][0] != '@': cpitem['icon_location'] = '@' + cpitem['icon_location'] cpitem['icon_handle'] = self.load_icon(cpitem['icon_location']) return cpitem