2014-11-05 22 views
0

在Python中,我試圖打開一個regedit Key來爲其添加String值。但是,它不知道OpenKey()ConnectRegistry方法。NameError:名稱'OpenKey'未使用winreg定義

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) 
+0

好吧,我正在導入winreg。我不明白爲什麼我需要做winreg.OpenKey – jerryh91 2014-11-05 16:46:47

回答

2

因爲您已經用import winreg導入它,所以您需要使用winreg.xxxxxx來引用該名稱空間中的所有方法。因此需要使用winreg.OpenKeywinreg.ConnectRegistry

或者,你可以做

from winreg import CreateKey, OpenKey, ConnectRegistry, etc 

這則允許您使用CreateKey等而不需要winreg前綴。

+0

我嘗試從winreg導入...,但編譯器說「名稱winreg沒有定義」 – jerryh91 2014-11-05 16:48:27

+0

哦,沒關係,我已經在winreg中導入這些函數。這是指我正在使用winreg.Method的一行 – jerryh91 2014-11-05 16:51:19

1

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

正如你所看到的,導入模塊不僅使可使用的模塊。它的所有內容(全局變量/函數/類/等)仍然保留在模塊的名稱空間內。


或者,你可以導入你打算直接使用的名稱:然後

from winreg import CreateKey, OpenKey, SetValueEx 

,你不需要用winreg.它們添加前綴。但我只會建議在使用幾個名稱時進行此操作。像這樣導入數十個名字會導致難看的代碼和混亂的全局名稱空間。