环境:Windows10,Python36(32bit)
Step1:首先需要安装Cython.。参考Cython[官方manual]的说明。
对于windows而言,需要安装编译器,这里选择Mingw。安装后需要设置环境MingW变量
PATH=C:\mingw-w64\x86_64-7.1.0-posix-seh-rt_v5-rev0\mingw32\bin.
然后添加文件c:\Python27\Lib\distutils\distutils.cfg。文件内容为
[build]
compiler = mingw32块内容
。按照官方的说明,在安装好MingW,并设置好环境变量后,就可以用pip install Cython安装Cython了。但我安装好后,在编译为pyd文件时总是报错:
ValueError: Unknown MS Compiler version 1900
C:\Program Files (x86)\Python36-32\Lib\distutils\cygwinccompiler.py
做如下修改
[参考]`
— cygwinccompiler.py
+++ cygwinccompiler.py
def get_msvcr():
elif msc_ver == '1600':
# VS2010 / MSVC 10.0
return ['msvcr100']
elif msc_ver == '1700':
# Visual Studio 2012 / Visual C++ 11.0
return ['msvcr110']
elif msc_ver == '1800':
# Visual Studio 2013 / Visual C++ 12.0
return ['msvcr120']
elif msc_ver == '1900':
# Visual Studio 2015 / Visual C++ 14.0
# "msvcr140.dll no longer exists"
return ['vcruntime140']
else:
# to do: can we make this futureproof?
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
然后添加vcruntime140.dll文件到C:\Python36\libs
Step2:安装 Cython
pip install Cython
Step3:将py文件编译为pyd[参考]。
编写setup.py文件
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext_modules = [Extension("my_code_cython",["my_code_cython.pyx"]),
Extension("another_code_cython",["another_code_cython.pyx"])]
setup(
name= 'Generic model class',
cmdclass = {'build_ext': build_ext},
include_dirs = [np.get_include()],
ext_modules = ext_modules)
然后在命令窗口运行下面命令,即可
python setup.py build_ext – --inplace
如果你想指定其他的编译器,或者前面没有添加distutils.cfg文件,可以在命令行指定,如,指定Mingw32 。注意inplace 和compiler前有两个"-- --"
python setup.py build_ext – --inplace – --compiler=mingw32
如果是VS编译器参考
python setup.py build_ext – --inplace – --compiler=msvc
另附,利用Cython将py转化为EXE的方法,可参考
参考来源:
https://stackoverflow.com/questions/34135280/valueerror-unknown-ms-compiler-version-1900
https://blog.youkuaiyun.com/md2017/article/details/78402189
https://stackoverflow.com/questions/36921961/how-to-create-a-pyd-file