覆盖 Python 设置工具的默认 include_dirs 和 library_dirs?

Overriding Python setuptool's default include_dirs and library_dirs?

我在 setup.py 中指定以下 include_dirslibrary_dirs

/opt/x86_64-sdk-linux/usr/bin/python3 setup.py build_ext \
--include-dirs=/opt/neon-poky-linux-gnueabi/usr/include/python3.5m/ \
--library-dirs=/opt/neon-poky-linux-gnueabi/usr/lib/ \
--rpath=/opt/neon-poky-linux-gnueabi/usr/lib/ \
--plat-name=linux_armv7l

但是,生成的 gcc 命令(执行 python3 setup.py build_ext 时)还包括包含路径,其中 python3 是 运行 来自(为了便于阅读,我添加了换行符):

arm-poky-linux-gnueabi-gcc \
--sysroot=/opt/neon-poky-linux-gnueabi \
-I. \
-I/opt/neon-poky-linux-gnueabi/usr/include/python3.5m/ \
-I/opt/x86_64-sdk-linux/usr/include/python3.5m \
-c py/constraint.cpp -o build/temp.linux-x86_64-3.5/py/constraint.o

第三个包含路径没有明确指定,但在编译时仍然使用。

我如何确保只使用我指定的 include-dirs

您需要覆盖 build_ext 命令,因为 the stdlib's build_ext ensures the Python header files, both platform specific and not, are always appended to the include paths.

下面是自定义 build_ext 命令的示例,该命令在选项完成后清理包含路径:

# setup.py

from distutils import sysconfig
from setuptools import setup
from setuptools.command.build_ext import build_ext as build_ext_orig


class build_ext(build_ext_orig):

    def finalize_options(self):
        super().finalize_options()
        py_include = sysconfig.get_python_inc()
        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
        for path in (py_include, plat_py_include, ):
            for _ in range(self.include_dirs.count(path)):
                self.include_dirs.remove(path)


setup(
    ...,
    cmdclass={'build_ext': build_ext},
)

更新

库目录的相同方法:在选项完成时清理列表:

class build_ext(build_ext_orig):

    def finalize_options(self):
        super().finalize_options()
        ...
        libdir = sysconfig.get_config_var('LIBDIR')
        for _ in range(self.library_dirs.count(libdir)):
            self.library_dirs.remove(libdir)