Search code examples
pythonpython-2.7pycharmwinreg

how to solve "[Error 5] Access is denied " during adding data to windows registry in python


this is my code:

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]

i have made an exe out of this by doing

pyinstaller.exe --onefile testDemo.py

it produces a "testDemo.exe" file. when i try to run it in cmd[with or without administrator mode] i get this.

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

how to solve it ?


Solution

  • The 3rd parameter reserved is missed in the call of OpenKey.

    winreg.OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ)

    reserved is a reserved integer, and must be zero. The default is zero.