我正在尝试使用winreg在Python中打开注册表键,以进行读写操作,但我一直遇到“PermissionError:[WinError 5]访问被拒绝”的问题。
首先,我手动更改了regedit中所需键的权限(如此教程所述)。这可以解决问题,但不太方便。我还注意到,例如为图形卡安装更新可能会删除旧键并创建新键,因此您必须在安装更新后调整权限,这很不实用。以管理员身份运行也没有帮助。
import winreg
reg_hive = winreg.HKEY_LOCAL_MACHINE
main_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render"
with winreg.ConnectRegistry(None, reg_hive) as Hive:
with winreg.OpenKey(
Hive, main_key, 0, winreg.KEY_ALL_ACCESS) as RenderKey:
get_subkey_tuple = winreg.QueryInfoKey(RenderKey)
# this tuple counts sub_key starting with 1
# we subtract -1 so we get the correct index for range()
subkey_indices = get_subkey_tuple[0] - 1
for i in range(0, subkey_indices):
sub_key = winreg.EnumKey(RenderKey, i)
final_key_string = main_key + "\\" + sub_key
print(final_key_string)
with winreg.OpenKey(Hive, final_key_string, 0, winreg.KEY_ALL_ACCESS) as local_key:
pass
“winreg.OpenKey”这些行会导致Permissionerror(我还没有手动更改regedit中权限的那些行)。我希望能够在不手动调整权限的情况下打开/读取/写入注册表键。
---编辑--- “reserved”参数与此有关吗?文档对此并没有详细说明。
只用两句话提到了“reserved”: “reserved是保留的整数,必须为零。默认值为零。” 和 “保留可以是任何东西-始终将零传递给API。” 后者仅适用于winreg.SetValueEX()。