python-2.7winreg

python script to read and write a path to registry


I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again. My code looks as below.

def OnOk(self, event):
    data1=self.field1.GetValue() #path selected in setting window
    aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
    keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
    try:
       SetValueEx(keyVal,"Log file",0,REG_SZ,data1)
    except EnvironmentError:
       pass
    CloseKey(keyVal)
    CloseKey(aReg)

I get a error like below:

Traceback (most recent call last):
File "D:\PROJECT\project.py", line 305, in OnOk
keyVal=OpenKey(aReg,r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
WindowsError: [Error 5] Access is denied

And to read from registry,the saved registry has to show up in the setting window.I tried with the below code.Though its working but not satisfied with the way i programmed it.Help me out for the better solution

key = OpenKey(HKEY_CURRENT_USER, r'Software\my path to\Registry', 0, KEY_READ)
    for i in range(4): 
        try:
            n,v,t = EnumValue(key,i)
            if i==0:
                self.field2.SetValue(v)
            elif i==1:
                self.field3.SetValue(v)
            elif i==2:
                self.field4.SetValue(v)
            elif i==3:
                self.field1.SetValue(v)
        except EnvironmentError:                                               
            pass
CloseKey(key)

Solution

  • Python script to read from registry is as follows:

    try:
        root_key=OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\my path to\Registry', 0, KEY_READ)
        [Pathname,regtype]=(QueryValueEx(root_key,"Pathname"))
        CloseKey(root_key)
        if (""==Pathname):
            raise WindowsError
    except WindowsError:
        return [""]
    

    Python script to write to the registry is:

    try:
        keyval=r"SOFTWARE\my path to\Registry"
        if not os.path.exists("keyval"):
            key = CreateKey(HKEY_CURRENT_USER,keyval)
        Registrykey= OpenKey(HKEY_CURRENT_USER, r"SOFTWARE\my path to\Registry", 0,KEY_WRITE)
        SetValueEx(Registrykey,"Pathname",0,REG_SZ,Pathname)
        CloseKey(Registrykey)
        return True
    except WindowsError:
        return False
    

    Hope it helps you all.Cheers:)