python 中拒绝访问

Access is denied in python

我想通过以下代码使用 python 添加注册表项:

import _winreg
from time import sleep
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Run',_winreg.KEY_SET_VALUE)
_winreg.SetValueEx(key,'Windows-Update',0,_winreg.REG_BINARY,'C:\Windows\System32\SystemSetting\Block.exe') 
key.Close()

但是它显示了这个错误WindowsError: [Error 5] Access is denied

有什么解决办法吗?

编辑 - 我已经运行它作为管理员

EDIT2 - 是否与 KEY_ALL_ACCESS

有关

运行 命令提示符中的 python 程序。 windows 中有一个 command prompt (Admin) 程序可用。或者只需右键单击 Command prompt 和 select Run as administratorRef

这与以管理员身份运行无关。我尝试以管理员身份运行,但仍然收到 Acces is denied 消息。

您必须使用默认为 0 的保留整数。

_winreg.OpenKey(key, sub_key[, res[, sam]]) ... res is a reserved integer, and must be zero. The default is zero.

所以,应该是这样的:

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

您实际上不必像建议的那样使用 KEY_ALL_ACCESS here。只需在 _winreg.KEY_SET_VALUE.

之前添加 0