How do I Open Windows Registry with write access in Python

TrinitronX picture TrinitronX · Feb 22, 2013 · Viewed 18.9k times · Source

I'm having some problems accessing the Windows 7 Registry with the _winreg.QueryValueEx function in the Python 2.7.3 _winreg module.

I am running the python process as Administrator, and can create new keys and values like this:

import _winreg as wreg
key = wreg.CreateKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject")
# Create new subkey
wreg.SetValue(key, 'NewSubkey', wreg.REG_SZ, 'testsubkey')
print wreg.QueryValue(key, 'NewSubKey')
# prints 'testsubkey'
# Create new value
wreg.SetValueEx(key, 'ValueName', 0, wreg.REG_SZ, 'testvalue')
print wreg.QueryValueEx(key,'ValueName')
# prints (u'testvalue', 1)
key.Close()

Keys in Windows Registry

However, when I re-open the same key and try to set the value, it gives me an Access is denied error:

key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",wreg.KEY_SET_VALUE)
wreg.SetValue(key, 'NewSubkey', wreg.REG_SZ, 'subkey_changed')
print wreg.QueryValue(key, 'NewSubkey')
# prints 'subkey_changed'
wreg.SetValueEx(key, 'ValueName', 0, wreg.REG_SZ, 'value_changed')

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    wreg.SetValueEx(key, 'ValueName', 0, wreg.REG_SZ, 'value_changed')
WindowsError: [Error 5] Access is denied

print wreg.QueryValueEx(key, 'ValueName')
# still prints: (u'testvalue', 1)
key.Close()

Interestingly, running as Administrator, I cannot open with KEY_WRITE or KEY_ALL_ACCESS access rights:

>>> key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",wreg.KEY_WRITE)

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",wreg.KEY_WRITE)
WindowsError: [Error 5] Access is denied
>>> key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",wreg.KEY_ALL_ACCESS)

Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",wreg.KEY_ALL_ACCESS)
WindowsError: [Error 5] Access is denied

Answer

Ivan Yan picture Ivan Yan · Feb 27, 2013

I solved the problem by doing:

key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",0, wreg.KEY_ALL_ACCESS)