Access Denied when entering value in windows registry by Python

1

In an attempt to create a function that inserts a value into a windows registry key, I came across an error. I use Windows 8 and Python 3.5. The function is as follows:

def inserir1(nome,path):
    import winreg
    key=winreg.OpenKey(winreg.HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Run')
    winreg.SetValueEx(key,nome,0,winreg.REG_SZ,path)
    key.Close()

inserirchave('teste','C:\Users\Usuario\Desktop\teste.txt')

The error that this script generates is as follows:

Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\Inserir Chave.py", line 16, in <module>
    inserir1(nome,path)
  File "C:\Users\Usuario\Desktop\Inserir Chave.py", line 8, in inserir1
    winreg.SetValueEx(key,nome,0,winreg.REG_SZ,path)
PermissionError: [WinError 5] Acesso negado

So I tried to run the script with administrator privileges, but failed, since the same error occurred even with those privileges. I tried doing it manually by regedit and there was no problem at all. How can I get permission to run this script?

    
asked by anonymous 02.01.2017 / 21:59

1 answer

1

Try this:

def inserir1(nome,path):
  key = OpenKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_ALL_ACCESS)
  key = CreateKey(HKEY_CURRENT_USER, keyVal)
  SetValueEx(key, nome, 0, REG_SZ, path)
  CloseKey(key)

inserir1('teste','C:\Users\Usuario\Desktop\teste.txt')
    
03.01.2017 / 03:55