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代码中过程一致。

posted on 2018-11-22 13:57  帅胡  阅读(443)  评论(0编辑  收藏  举报

导航