名称错误:名称“OpenKey”未使用winreg定义

2024-09-27 21:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我试图打开一个regedit键来向它添加字符串值。但是,它不知何故没有识别OpenKey()或{}方法。在

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)

Tags: pathnameimportascurrentkey2userwinreg
2条回答

当您使用import winreg导入它时,您需要使用winreg.xxxxxx引用该名称空间中的所有方法。在

因此,您需要使用winreg.OpenKey和{}。在

或者,你可以

from winreg import CreateKey, OpenKey, ConnectRegistry, etc

这将允许您使用CreateKey,等等,而不需要winreg前缀。在

OpenKey函数位于winreg模块内的。意思是,您需要在它前面加上winreg.才能访问它:

keyVal = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r"AppEvents\{Key2}", 0,KEY_WRITE)
#        ^^^^^^^

对于ConnectRegistrySetValueEx,以及您在模块中使用的任何其他名称也是一样的。您可以在docs中了解此行为:

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

如您所见,导入模块只会使模块可用。它的所有内容(global/functions/classes/etc)仍然保留在模块的命名空间中。在


或者,可以直接导入计划使用的名称:

^{pr2}$

然后,不需要在它们前面加上winreg.。但我只建议你在使用几个名字的时候这样做。像这样导入几十个名称会导致难看的代码和混乱的全局命名空间。在

相关问题 更多 >

    热门问题