如何解决在python中向Windows注册表添加数据时出现“[错误5]访问被拒绝”的问题

问题描述 投票:0回答:2

这是我的代码:

import _winreg
import sys

try:
    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run',
                          _winreg.KEY_SET_VALUE)
    _winreg.SetValueEx(key, 'pytest', 0, _winreg.REG_BINARY, 'C:\Users\Default\Desktop\est.py')
    _winreg.QueryInfoKey(key)
    key.Close()
    print "Successfully Added"
except:
    print "Unexpected error:", sys.exc_info()[1],sys.exc_info()[0]

我已经通过这样做

制作了一个exe文件
pyinstaller.exe --onefile testDemo.py

它会生成一个“testDemo.exe”文件。 当我尝试在 cmd [有或没有管理员模式] 中运行它时,我得到了这个。

Unexpected error: [Error 5] Access is denied <type 'exceptions.WindowsError'>

如何解决?

python python-2.7 pycharm winreg
2个回答
2
投票

OpenKey 调用中遗漏了第三个参数reserved

winreg.OpenKeyEx(密钥,子密钥,保留= 0,访问= KEY_READ)

reserved 是保留整数,并且必须为零。默认为零。


0
投票

您只拥有

Set
钥匙的权限,而无权
Read
它! 有趣的是,尝试读取密钥时从来没有任何例外......

请参阅文档

请使用

winreg.KEY_ALL_ACCESS

© www.soinside.com 2019 - 2024. All rights reserved.