#PYTHON# 编译并安装第三方模块遇到的问题

 

配置一个环境偶尔很重要,因为会了解到很多操作系统细节的知识。

今天在通过easy_install安装milk【机器学习库】库的时候,出现了以下现象: Unable to find vcvarsall.bat。

开始以为是easy_install的原因,然后我将milk库下载到本地,用python setup.py install安装,没有想到出现了同样的错误提示。于是,今天吐槽一下解决方案: 为何我们有时安装的时候,又没有提示如此的错误呢,原因是milk有C文件,在安装的时候需要进行编译,就需要用到其,主要是为了让python找到相应的编译器,其实就是告诉python ml, link这二个编译,链接的二进制文件。


第一,找到报错的源文件msvc9compiler.py【Lib/distutils/】,发现出现在函数

def find_vcvarsall(version):
    """Find the vcvarsall.bat file

    At first it tries to find the productdir of VS 2008 in the registry. If
    that fails it falls back to the VS90COMNTOOLS env var.
    """
    vsbase = VS_BASE % version
    try:
        productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
                                   "productdir")
    except KeyError:
        productdir = None

    # trying Express edition
    if productdir is None:
        vsbase = VSEXPRESS_BASE % version
        try:
            productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
                                       "productdir")
        except KeyError:
            productdir = None
            log.debug("Unable to find productdir in registry")

    if not productdir or not os.path.isdir(productdir):
        toolskey = "VS%0.f0COMNTOOLS" % version
        toolsdir = os.environ.get(toolskey, None)

        if toolsdir and os.path.isdir(toolsdir):
            productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
            productdir = os.path.abspath(productdir)
            if not os.path.isdir(productdir):
                log.debug("%s is not a valid directory" % productdir)
                return None
        else:
            log.debug("Env var %s is not set or invalid" % toolskey)
    if not productdir:
        log.debug("No productdir found")
        return None
    vcvarsall = os.path.join(productdir, "vcvarsall.bat")
    if os.path.isfile(vcvarsall):
        return vcvarsall
    log.debug("Unable to find vcvarsall.bat")
    return None

通过理解源码,python解释器,会依搜索注册表中VS的目录,接着搜索环境变量为VS90COMNTOOLS的目录,结果我看了一下我的电脑环境变量没有该值,只有VS100COMNTOOLS,纳闷,原来我安装的是VS2010,后来有人说,python2.7默认的VS版本是2008.我们有二种方式,来找出其默认的编译器:

>>> import sys
>>> sys.version
'2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]'
>>>

 

MSC的版本是1500,具体可以看这里。可以,发现其是VS2008的版本,对应的环境变量是VS90COMNTOOLS,如果恰好你的电脑上的配置是VS2008,那么当然不会有如此错误,可是我的电脑是VS2010。如果你不相信,你可以继续看msvc9compiler.py文件中的get_build_version()函数,直接调用其,其值是9.0,对应的正是VS90COMNTOOLS环境变量。

那么, 我们可以直接在电脑上添加一个VS90COMNTOOLS的环境变量,其值等于VS100COMNTOOLS即可。记得,注销或重启系统之后方才有效。

可是,祸不单行,在解决以上问题之后,在windows上安装milk的时候,第二问题就是在编译的的阶段出了问题。

不过,这个问题我还真心不知道怎么解决,不过,我们可以换一种思维,难道编译C只有微软的东西么,对,很多其他的东西,如mingw32等等,所以,我们可以再编译的时候选择自己指定的编译器

python setup.py build –compiler==mingw32

即可,哈哈,而且居然还成功了,当然你需要安装mingw32,记得设置好相应的环境变量,否者找不到G++等编译器。明白编译可以用其他的工具就可以啦。这种方式,也让我们窥见python以何种方式调用C文件。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。