windows安裝python2.7后的注冊(registry)問題


【提要】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代碼中過程一致。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM