在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)
当您使用
import winreg
导入它时,您需要使用winreg.xxxxxx
引用该名称空间中的所有方法。在因此,您需要使用}。在
winreg.OpenKey
和{或者,你可以
这将允许您使用
CreateKey
,等等,而不需要winreg
前缀。在OpenKey
函数位于winreg
模块内的。意思是,您需要在它前面加上winreg.
才能访问它:对于
ConnectRegistry
,SetValueEx
,以及您在模块中使用的任何其他名称也是一样的。您可以在docs中了解此行为:如您所见,导入模块只会使模块可用。它的所有内容(global/functions/classes/etc)仍然保留在模块的命名空间中。在
或者,可以直接导入计划使用的名称:
^{pr2}$然后,不需要在它们前面加上
winreg.
。但我只建议你在使用几个名字的时候这样做。像这样导入几十个名称会导致难看的代码和混乱的全局命名空间。在相关问题 更多 >
编程相关推荐