我正在开发一个带有 setup.py 的 Python 项目,它有类似这样的内容1:
setup(
cmdclass={"build_ext": my_build_ext},
ext_modules=[
Extension("A", ["a.c", "common.c"]),
Extension("B", ["b.c", "common.c"])
]
)
我在并行构建模块时遇到了一个问题,似乎一个模块试图读取
common.o
/common.obj
,而另一个模块正在编译它,但失败了。有没有办法让 setuptools 将每个模块的 C 文件编译到它们自己的构建目录中,这样它们就不会互相覆盖?
我通过在自定义
build_extension()
类中覆盖 build_ext
找到了一个潜在的解决方案。
import copy, os
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
class my_build_ext(build_ext):
def build_extension(self, ext):
# Append the extension name to the temp build directory
# so that each module builds to its own directory.
# We need to make a (shallow) copy of 'self' here
# so that we don't overwrite this value when running in parallel.
self_copy = copy.copy(self)
self_copy.build_temp = os.path.join(self.build_temp, ext.name)
build_ext.build_extension(self_copy, ext)
这对我有用,但感觉有点像黑客,所以它可能不适用于所有情况。