pythonregeditwinreg

NameError: name 'OpenKey' is not defined using winreg


In Python, I'm trying to open a regedit Key to add String value to it. However, it's somehow not recognizing the OpenKey() or ConnectRegistry method.

import winreg
import sys
#Create 2 keys with unique GUIDs as Names

KeyName1 = "AppEvents\{Key1}"
KeyName2 = "AppEvents\{Key2}"
KeyName1_Path = "C:\Install\Monitor\Path.asmtx"


winreg.CreateKey(winreg.HKEY_CURRENT_USER, KeyName1)
winreg.CreateKey(winreg.HKEY_CURRENT_USER,  KeyName2)

#Add String as Path
# aReg = ConnectRegistry(None,HKEY_CURRENT_USER) #NameError: name 'ConnectRegistry' is not defined

keyVal=OpenKey(winreg.HKEY_CURRENT_USER,r"AppEvents\{Key2}", 0,KEY_WRITE) ameError: name 'OpenKey' is not defined


SetValueEx(keyVal,"Path",0,REG_SZ, KeyName1_Path)

Solution

  • As you have imported it with import winreg you need to refer to all methods within that name space using winreg.xxxxxx.

    As such, you need to use winreg.OpenKey and winreg.ConnectRegistry.

    Alternatively, you could do

    from winreg import CreateKey, OpenKey, ConnectRegistry, etc
    

    This would then allow you to use CreateKey, etc without the need of the winreg prefix.