windows安裝python2.7後的註冊(registry)問題
阿新 • • 發佈:2018-11-22
【提要】win平臺上,python2.7官網的安裝包在安裝後不會新增環境變數且不會把安裝資訊寫入登錄檔。
把python和pip的安裝路徑新增到環境變數是做python開發必要的一步,而寫入登錄檔的原因是,有些python包以
windows installer的形式安裝,安裝的時候需要用到python的登錄檔資訊,比如,numpy, scipy。
安裝步驟:
(1)到python官網下載安裝包,www.python.org/downloads,執行安裝;
(2)把python.exe所在路徑(python安裝路徑)以及pip.exe路徑(python安裝路徑下的Script檔案加)新增到path環境變數。
比如我的python在這裡:“C:\Python27”,那麼新增路徑:“C:\Python27”和“C:\Python27\Scripts”到path環境變數;
(3)在登錄檔中新增python註冊資訊,用於python可以操作windows的登錄檔,可以執行python檔案來完成此步操作,
以下為python原始碼,把它拷貝出來,放在任意位置,用python執行即可。
1 import sys 2 3 4 from _winreg import * 5 6 # tweak as necessary 7 version = sys.version[:3] 8 installpath = sys.prefix 9 regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version) 10 installkey = "InstallPath" 11 pythonkey = "PythonPath" 12 pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % ( 13 installpath, installpath, installpath 14 ) 15 16 def RegisterPy(): 17 print "begin RegisterPy " 18 try: 19 print "open key : %s"%regpath 20 reg = OpenKey(HKEY_CURRENT_USER, regpath) 21 except EnvironmentError as e: 22 try: 23 reg = CreateKey(HKEY_CURRENT_USER, regpath) 24 SetValue(reg, installkey, REG_SZ, installpath) 25 SetValue(reg, pythonkey, REG_SZ, pythonpath) 26 CloseKey(reg) 27 except: 28 print "*** EXCEPT: Unable to register!" 29 return 30 31 print "--- Python", version, "is now registered!" 32 return 33 34 35 if (QueryValue(reg, installkey) == installpath and 36 QueryValue(reg, pythonkey) == pythonpath): 37 CloseKey(reg) 38 print "=== Python", version, "is already registered!" 39 return CloseKey(reg) 40 41 print "*** ERROR:Unable to register!" 42 print "*** REASON:You probably have another Python installation!" 43 44 def UnRegisterPy(): 45 #print "begin UnRegisterPy " 46 try: 47 print "open HKEY_CURRENT_USER key=%s"%(regpath) 48 reg = OpenKey(HKEY_CURRENT_USER, regpath) 49 #reg = OpenKey(HKEY_LOCAL_MACHINE, regpath) 50 except EnvironmentError: 51 print "*** Python not registered?!" 52 return 53 try: 54 DeleteKey(reg, installkey) 55 DeleteKey(reg, pythonkey) 56 DeleteKey(HKEY_LOCAL_MACHINE, regpath) 57 except: 58 print "*** Unable to un-register!" 59 else: 60 print "--- Python", version, "is no longer registered!" 61 62 if __name__ == "__main__": 63 RegisterPy()
如下圖所示,出現Pyhton 2.7 is now registered!字樣即為註冊成功。
在登錄檔中也能看到相應的資訊:
如果由於諸如安裝後又解除安裝了多個版本python的原因導致登錄檔資訊不對,可以直接手動編輯登錄檔,然後重新註冊。
手動在登錄檔中添加註冊資訊的方法跟上述python程式碼中過程一致。