Python win32api.RegCloseKey() Examples

The following are 23 code examples of win32api.RegCloseKey(). 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 win32api , or try the search function .
Example #1
Source File: regedit.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: browseProjects.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: util.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def deleteKey(self, hKey, subKey):
        """
        Recursively remove registry keys.
        """
        try:
            hKey = win32api.RegOpenKeyEx(hKey, subKey, 0,
                                         win32con.KEY_ALL_ACCESS)
            try:
                while True:
                    s = win32api.RegEnumKey(hKey, 0)
                    self.deleteKey(hKey, s)
                    print("CleanupRegistry: Removing sub-key '{}'".format(s))
                    win32api.RegDeleteKey(hKey, s)
            except win32api.error:
                pass
            finally:
                win32api.RegCloseKey(hKey)
        except:
            print("Warning: Unable to open registry key!")
            pass 
Example #4
Source File: regutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: registry.py    From code with MIT License 5 votes vote down vote up
def close(self):
        if self.hKey:
            Api.RegCloseKey(self.hKey)
            self.hKey = None 
Example #6
Source File: msw.py    From wxGlade with MIT License 5 votes vote down vote up
def __del__(self):
        # close key
        if self.handle is not None:
            win32api.RegCloseKey(self.handle)
            self.handle = None
        # XXX todo: delete ourselves if key has been created newly but no value has been written 
Example #7
Source File: recipe-528896.py    From code with MIT License 5 votes vote down vote up
def WriteRegistryValue(hiveKey, key, name, data, typeId=win32con.REG_SZ):
    """ Write one value to Windows registry. If 'name' is empty string, writes default value.
        Creates subkeys as necessary"""
    try:
        keyHandle = OpenRegistryKey(hiveKey, key)
        win32api.RegSetValueEx(keyHandle, name, 0, typeId, data)
        win32api.RegCloseKey(keyHandle)
    except Exception, e:
        print "WriteRegistryValue failed:", hiveKey, name, e 
Example #8
Source File: recipe-528896.py    From code with MIT License 5 votes vote down vote up
def ReadRegistryValue(hiveKey, key, name=""):
    """ Read one value from Windows registry. If 'name' is empty string, reads default value."""
    data = typeId = None
    try:
        keyHandle = win32api.RegOpenKeyEx(hiveKey, key, 0, win32con.KEY_ALL_ACCESS)
        data, typeId = win32api.RegQueryValueEx(keyHandle, name)
        win32api.RegCloseKey(keyHandle)
    except Exception, e:
        print "ReadRegistryValue failed:", hiveKey, key, name, e 
Example #9
Source File: recipe-576431.py    From code with MIT License 5 votes vote down vote up
def modifyVariableInRegister( name , value ):
    key = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER,"Environment",0,win32con.KEY_ALL_ACCESS)
    if not key : raise
    win32api.RegSetValueEx( key , name , 0 , win32con.REG_SZ , value )
    win32api.RegCloseKey( key ) 
Example #10
Source File: recipe-174627.py    From code with MIT License 5 votes vote down vote up
def close(self):
        try:
            win32api.RegCloseKey(self.keyhandle)
        except:
            pass 
Example #11
Source File: register.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #12
Source File: combrowse.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 
Example #13
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: regutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 
Example #16
Source File: win32evtlogutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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. 
Example #17
Source File: regedit.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #18
Source File: regedit.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #19
Source File: regedit.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #20
Source File: regsetup.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def SetupCore(searchPaths):
    """Setup the core Python information in the registry.

       This function makes no assumptions about the current state of sys.path.

       After this function has completed, you should have access to the standard
       Python library, and the standard Win32 extensions
    """

    import sys
    for path in searchPaths:
        sys.path.append(path)

    import os
    import regutil, win32api,win32con

    installPath, corePaths = LocatePythonCore(searchPaths)
    # Register the core Pythonpath.
    print corePaths
    regutil.RegisterNamedPath(None, ';'.join(corePaths))

    # Register the install path.
    hKey = win32api.RegCreateKey(regutil.GetRootKey() , regutil.BuildDefaultPythonKey())
    try:
        # Core Paths.
        win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath)
    finally:
        win32api.RegCloseKey(hKey)

    # Register the win32 core paths.
    win32paths = os.path.abspath( os.path.split(win32api.__file__)[0]) + ";" + \
                 os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path ) )[0] )

    # Python has builtin support for finding a "DLLs" directory, but
    # not a PCBuild.  Having it in the core paths means it is ignored when
    # an EXE not in the Python dir is hosting us - so we add it as a named
    # value
    check = os.path.join(sys.prefix, "PCBuild")
    if "64 bit" in sys.version:
        check = os.path.join(check, "amd64")
    if os.path.isdir(check):
        regutil.RegisterNamedPath("PCBuild",check) 
Example #21
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
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 
Example #22
Source File: win32evtlogutil.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
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) 
Example #23
Source File: debugger.py    From peach with Mozilla Public License 2.0 4 votes vote down vote up
def LocateWinDbg(self):
            """
            This method also exists in process.PageHeap!
            """

            try:

                hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\DebuggingTools")

            except:

                # Lets try a few common places before failing.
                pgPaths = [
                    "c:\\",
                    os.environ["SystemDrive"] + "\\",
                    os.environ["ProgramFiles"],
                ]
                if "ProgramW6432" in os.environ:
                    pgPaths.append(os.environ["ProgramW6432"])
                if "ProgramFiles(x86)" in os.environ:
                    pgPaths.append(os.environ["ProgramFiles(x86)"])

                dbgPaths = [
                    "Debuggers",
                    "Debugger",
                    "Debugging Tools for Windows",
                    "Debugging Tools for Windows (x64)",
                    "Debugging Tools for Windows (x86)",
                ]

                for p in pgPaths:
                    for d in dbgPaths:
                        testPath = os.path.join(p, d)

                        if os.path.exists(testPath):
                            return testPath

                return None

            val, type = win32api.RegQueryValueEx(hkey, "WinDbg")
            win32api.RegCloseKey(hkey)
            return val