zmbq
zmbq

Reputation: 39013

Access denied writing to HKEY_CURRENT_USER in Python

I'm trying to update the user's PATH in Windows. I have a function similar to this one:

import winreg

def add_to_path():
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', winreg.KEY_SET_VALUE | winreg.KEY_QUERY_VALUE) as key:
        path, type = winreg.QueryValueEx(key, 'Path')
        path += ';d:\\'

        winreg.SetValueEx(key, 'OtherPath', 0, type, path)
    

This function fails on the call to SetValueEx with an access denied error. If I try to open the key with KEY_WRITE I get an access denied on the call to OpenKey.

What am I doing wrong?

Upvotes: 0

Views: 327

Answers (1)

zmbq
zmbq

Reputation: 39013

Turns out I missed the third argument to winreg.OpenKey - reserved, the way to open the key is:

winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', access=winreg.KEY_SET_VALUE | winreg.KEY_QUERY_VALUE)

Upvotes: 2

Related Questions