运行 python setup.py 安装时强制编译

Force compiler when running python setup.py install

在 运行 python setup.py install 时,有没有办法明确强制编译器构建 Cython 扩展?其中 setup.py 的形式为:

import os.path
import numpy as np
from setuptools import setup, find_packages, Extension
from Cython.Distutils import build_ext

setup(name='test',
  packages=find_packages(),
  cmdclass={'build_ext': build_ext},
  ext_modules = [ Extension("test.func", ["test/func.pyx"]) ],
  include_dirs=[np.get_include()]
 )

我正在尝试使用 Anaconda 3.16、Python 3.4、setuptools 18、Numpy 1.9 和 Cython 0.24 在 Windows 8.1 x64 上安装一个包。部署脚本改编自 Cython wiki and this Stack Overflow 答案。

Makefile.bat

:: create and activate a virtual environement with conda
conda create --yes -n test_env cython setuptools=18 pywin32 libpython numpy=1.9 python=3
call activate test_env

:: activate the MS SDK compiler as explained in the Cython wiki
cd C:\Program Files\Microsoft SDKs\Windows\v7.1\
set MSSdk=1
set DISTUTILS_USE_SDK=1
@call .\Bin\SetEnv /x64 /release 

cd C:\test
python setup.py install

问题是在这种情况下setup.py install仍然使用conda附带的mingw编译器而不是MS Windows SDK 7.1。

有没有办法强制编译器构建这个包,例如,通过编辑 setup.py?

您可以在名为 setup.cfg(与 setup.py 平行放置)的单独文件中为 distutils 提供(默认)命令行参数。有关详细信息,请参阅 docs。要设置编译器,请使用类似:

[build]
compiler=msvc

现在调用python setup.py build等同于调用python setup.py build --compiler=msvc。 (您仍然可以通过调用 python setup.py build --compiler=someothercompiler 指示 distutils 使用其他编译器)

现在您已经(成功地指示 distutils 使用 a msvc 编译器。不幸的是,没有选项告诉它 哪个 msvc 编译器使用。基本上有两种选择:

一个: 什么都不做,distutils 将尝试定位 vcvarsall.bat 并使用它来设置环境。 vcvarsall.bat(以及它为其设置环境的编译器)是 Visual Studio 的一部分,因此您必须安装它才能工作。

二: 安装 Windows SDK 并告诉 distutils 使用它。请注意,名称 DISUTILS_USE_SDK 相当具有误导性(至少在我看来)。它实际上并没有告诉 distutils 使用 SDK(它是 setenv.bat)来设置环境,而是意味着 distutils 应该假设环境已经设置好了。这就是为什么你必须使用某种 Makefile.bat 正如你在 OP 中所示。

旁注: VisualStudio 或 Windows SDK 的具体版本取决于目标 python 版本。

备注:在 linux 上,您可以使用许多 autoconf 环境变量。对于编译器

CC=mpicc python setup.py build_ext -i

好吧,我在我的案例中发现了一个技巧:我想使用 MSVC14.0(来自 buildtools 2015)而不是 MSVC14.1(buildtools 2017)。我编辑了文件 Lib\distutils_msvccompiler.py。有一个方法

_find_vcvarsall 

正在调用

best_version, best_dir = _find_vc2017()

我将此调用替换为

best_version, best_dir = _find_vc2015()

不要忘记在编译后撤消这个肮脏的把戏。

我最后把它放在 setup.py 的开头以强制 visual2015

当 运行 在非 bat 环境中并且无法从外部启动 vcvarsall 时很有用

if sys.platform == 'win32':
    # patch env with vcvarsall.bat from vs2015 (vc14)
    try:
        cmd = '"{}..\..\VC\vcvarsall.bat" x86_amd64 >nul 2>&1 && set'.format(environ['VS140COMNTOOLS'])
        out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True)
    except:
        print("Error executing {}".format(cmd))
        raise

    for key, _, value in (line.partition('=') for line in out.splitlines()):
        if key and value:
            os.environ[key] = value

    # inform setuptools that the env is already set
    os.environ['DISTUTILS_USE_SDK'] = '1'