Python 3.8 搭配 Cython 和 Mingw64 8.1.0生成PYD的一些坑
python批量编译pyd并保持原有的目录结构
参考 https://blog.csdn.net/joyopirate/article/details/118609151
使用时,将文件放在项目的最外层的目录即可
#-* -coding: UTF-8 -* -
__author__ = 'Arvin'
__modifier__ = 'zy'
__modifier__ = 'zzh'
"""
执行前提:
系统安装python-devel 和 gcc
Python安装cython
编译某个文件夹:
python py2so.py BigoModel
生成结果:
目录 build 下
生成完成后:
启动文件还需要py/pyc担当,须将启动的py/pyc拷贝到编译目录并删除so文件
zy修改:
原程序在编译之后,所有文件夹里面的py文件编译得到的库文件全都放在build里面,而丧失了原来的目录架构,导致互相之间的调用出问题。
这里简单增加一些语句,实现编译后的库文件保留原来的py文件的目录架构
但是这样子做的话,需要一个个地编译。而不能批量传入,会比较慢。暂时只想到这个办法
zzh修改
增加去掉中间.cp38-win_amd64的功能
"""
import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
starttime = time.time()
setupfile = os.path.join(os.path.abspath('.'), __file__)
def getpy(basepath=os.path.abspath('.'), parentpath='', name='', build_dir="build",
excepts=(), copyOther=False, delC=False):
"""
获取py文件的路径
:param basepath: 根路径
:param parentpath: 父路径
:param name: 文件/夹
:param excepts: 排除文件
:param copy: 是否copy其他文件
:return: py文件的迭代器
"""
# 文件夹的全路径
fullpath = os.path.join(basepath, parentpath, name)
# 遍历文件夹
for fname in os.listdir(fullpath):
ffile = os.path.join(fullpath, fname)
# 假如是文件夹 而且 不是build文件夹 而且不是‘.’开头
if os.path.isdir(ffile) and ffile != os.path.join(basepath, build_dir) and not fname.startswith('.'):
# 递归调用
for f in getpy(basepath, os.path.join(parentpath, name), fname, build_dir, excepts, copyOther, delC):
yield f
# 假如是文件
elif os.path.isfile(ffile):
# print("\t", basepath, parentpath, name, ffile)
# 获取文件的后缀名
ext = os.path.splitext(fname)[1]
# 假如是c文件,而且是本次编译生成的(最后修改时间 > 本次编译的开始时间),且指定了要执行删除操作,就删除
if ext == ".c":
if delC and os.stat(ffile).st_mtime > starttime:
os.remove(ffile)
# 假如 这个文件不是本文件,而且不是pyc、pyx文件
elif ffile not in excepts and ext not in('.pyc', '.pyx'):
# print("\t\t", basepath, parentpath, name, ffile)
# 假如是py文件
if ext in('.py', '.pyx') and not fname.startswith('__'):
yield os.path.join(parentpath, name, fname)
# 假如需要复制
elif copyOther:
print('copy---------')
# 目标文件夹为build_dir的目录源码目录
dstdir = os.path.join(basepath, build_dir, parentpath, name)
# 假如路径不存在,创建路径
if not os.path.isdir(dstdir):
os.makedirs(dstdir)
# 复制文件
shutil.copyfile(ffile, os.path.join(dstdir, fname))
print("------------", ffile, os.path.join(dstdir, fname))
else:
pass
if __name__ == "__main__":
# 当前路径
currdir = os.path.abspath('.')
# 要编译的源代码文件夹
parentpath = sys.argv[1] if len(sys.argv) > 1 else "."
# currdir为源代码路径上一层, parentpath为源代码文件夹
currdir, parentpath = os.path.split(currdir if parentpath == "." else os.path.abspath(parentpath))
# 用来存放编译文件的build文件夹
build_dir = os.path.join(parentpath, "build")
build_tmp_dir = os.path.join(build_dir, "temp")
print("start:", currdir, parentpath, build_dir)
# cd到currdir, 也就是源代码文件夹的上一层
os.chdir(currdir)
try:
#获取py列表
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile)))
print("build these:", module_list)
# 编译
# setup(ext_modules=cythonize(module_list), script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
for filePath in module_list:
path, file = os.path.split(filePath)
absPath = os.path.join(build_dir, path)
# 假如路径不存在,创建路径
if not os.path.isdir(absPath):
os.makedirs(absPath)
# 编译
setup(ext_modules=cythonize(filePath), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir])
# # 清理缓存文件夹
# if os.path.exists(build_tmp_dir):
# shutil.rmtree(build_tmp_dir)
# 将编译好的pyd文件拷贝指build文件路径中 这一句貌似没执行(因为原本就已经在build文件夹里面了)
print("begin copy")
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), copyOther=True))
except Exception as ex:
print("error! ", ex)
finally:
print("cleaning...")
# 清理生成的中间C文件
module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), delC=True))
# 清理缓存文件夹
if os.path.exists(build_tmp_dir):
shutil.rmtree(build_tmp_dir)
# 去掉中间的拓展名
for root, dirs, files in os.walk(currdir):
for name in files:
if name.endswith(".pyd"):
file_path = os.path.join(root, name)
filename = file_path.split('.cp')[0]
os.rename('%s.cp38-win_amd64.pyd' % (filename), '%s.pyd' % (filename))
print("complete! time:", time.time()-starttime, 's')
第一个坑
默认情况下,Cython 默认使用 Python2 编译,即使您使用的是 Python3(编辑 2021:Cython3 将改变这一点,并在很大程度上默认使用 Python3 语法)
用 Cython 编译如下语句时 x = print
会报错 Expected an identifier or literal
print 不是标识符或文字,因为在 Python2 语法下它是一个特殊语句。
在 Python3 语法下,print 是一个函数,所以这很有意义。
如果将 Cython 编译语法改为 Python3 时可以正常编译
解决方法如下
-
被编译文件中添加如下语句
#cython: language_level=3
-
或在setup.py中将其指定为编译器指令:
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize('cy_print_test.pyx', compiler_directives={'language_level': 3}),
)
- 如果你使用上面提供的批量编译脚本,可做如下修改
setup(ext_modules=cythonize(filePath), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir])
setup(ext_modules=cythonize(filePath, language_level=3), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir])
第二个坑 - error: Unable to find vcvarsall.bat
第一种方法安装 Visual Studio,这确实是解决问题最快的方法,如果你选择这种可以跳过此坑
第二种方法坚持使用 MinGW,强迫症选项,因为 VS 实在太大了
这里对 MinGW 做个简单介绍先,即 Minimalist GNU For Windows。它是一些头文件和端口库的集合,该集合允许在没有第三方动态链接库的情况下使用 GCC(GNU Compiler C)产生 Windows32 程序。MinGW 并不只是一个 C/C++ 编译器,而是一套 GNU 工具集合。除开 GCC (GNU 编译器集合) 以外,MinGW 还包含有一些其他的 GNU 程序开发工具 (比如 gawk bison 等等)。
他们的关系是python源码经过cython生成c文件,再通过MinGW编译成pyd动态链接库。pyd作为python的动态链接库,可以被py程序直接import使用。
MinGW 安装
- 下载离线免安装版(https://sourceforge.net/projects/mingw-w64/files/mingw-w64/) 请下载最新的x86_64-posix-seh版本,win32版本不支持c++11的thread库),解压到非中文目录中(路径中不得包含中文),建议解压到 C:\mingw64
- 在环境变量path中添加路径D:\mingw64\bin(建议用户变量和系统变量都添加上路径)。
MinGw 配置
- 添加distutils.cfg,在Python安装目录\Lib\distutils\中添加distutils.cfg文件,并写入以下内容。
[build]
compiler=mingw32
[build_ext]
compiler = mingw32
- 将编译器指向MinGw, 首先使用如下命令 get 当前 MSVC 的 version
import sys
msc_pos = sys.version.find('MSC v.')
msc_ver = sys.version[msc_pos+6:msc_pos+10]
print(msc_ver)
修改 Python 安装目录 \Lib\distutils\cygwinccompiler.py 文件,在 get_msvcr 函数中 else 之前添加判断代码,判断 msc_ver为1928,并指定编译器为 vcruntime140。
elif msc_ver == '1928':
# MinGW
return ['vcruntime140']
到此时已经可以解决 Unable to find vcvarsall.bat 的问题,但是新问题也来了
第三个坑 - error: enumerator value for '__pyx_check_sizeof_voidp'
解决:执行cmd编译命令是需加上-DMS_WIN64参数
python build.py build_ext --inplace -DMS_WIN64
当然如果你使用的是本文提供的脚本你可以做如下修改
setup(ext_modules=cythonize(filePath), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir])
setup(ext_modules=cythonize(filePath, language_level=3), script_args=["build_ext", "-b", absPath, "-t", build_tmp_dir, "--inplace", "-DMS_WIN64"])
第四个坑 - ld.exe: cannot find -lvcruntime140
下载对应32位或者64位的 vcruntime140.dll 文件复制到任意一个 MinGW gcc 库文件目录下
下载地址为 https://www.dll-files.com/vcruntime140.dll.html
MinGW gcc 库文件目录可以通过 gcc -print-search-dirs 命令即可查询到相应目录
最后放完之后记得重启CMD,然后终于可以顺利编译安装,泪目。。。
参考:
Python使用Cython+MinGW编译Pyd动态链接库
笔记:使用MinGW取代MSVC在Windows 10中编译Python库