12

我 在使用 Python 2.7.3 _winreg模块中的_winreg.QueryValueEx函数访问 Windows 7 注册表时遇到了一些问题。

我以管理员身份运行 python 进程,并且可以创建新的键和值,如下所示:

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()

Windows 注册表中的键

但是,当我重新打开同一个键并尝试设置值时,它给了我一个Access is denied错误:

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()

有趣的是,以管理员身份运行,我无法使用KEY_WRITEKEY_ALL_ACCESS访问权限打开:

>>> 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
4

1 回答 1

24

我通过这样做解决了这个问题:

key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, "Software\\TestCompany\\TestProject",0, wreg.KEY_ALL_ACCESS)
于 2013-02-27T08:49:12.317 回答