Distutils 在构建 python 扩展时部分忽略 CC 环境变量

Distutils partially ignoring CC environment variable when building python extension

我正在尝试安装 subprocess32 python 模块 (https://github.com/google/python-subprocess32),但在使用 distutils 时遇到了一些问题。该模块包含一个必须构建的 C 扩展,但是当我 运行 pip install .python setup.py install 我得到以下输出:

...
creating build
creating build/temp.linux-x86_64-2.7
/non/existent/path/gcc -pthread -fPIC ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
unable to execute '/non/existent/path/gcc': No such file or directory

显然 distutils 出于某种原因使用了错误的 gcc 路径。然后我尝试使用 export CC=/correct/path/to/gcc 手动指定 gcc 的正确路径,我得到了这个输出:

building '_posixsubprocess' extension
creating build/temp.linux-x86_64-2.7
/correct/path/to/gcc -fPIC -fno-strict-aliasing -g -O2 ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
/non/existent/path/gcc -pthread -shared ... build/temp.linux-x86_64-2.7/_posixsubprocess.o -o build/lib.linux-x86_64-2.7/_posixsubprocess.so
unable to execute '/non/existent/path/gcc': No such file or directory

原来有问题的命令现在使用了正确的路径,但它仍然试图使用不正确的 gcc 位置来构建共享库。我需要指定另一个环境变量来纠正此行为吗?

我通过自己编译扩展来解决这个问题,从 setup.py 中删除对扩展的引用,安装包,然后将编译的文件复制到正确的位置。我不会将此答案标记为已接受,因为我确信有更好的方法..

我和你试验过完全相同的问题。我花了一些时间深入研究 distutils 源代码并找到了问题所在。

distutils 将使用构建 Python 时的 link 配置。在这种情况下,用于构建 python 的 gcc 与您用于构建扩展的 gcc 不同。

运行 这个命令也见默认的 link 命令:

python2 "from distutils.sysconfig import get_config_var; print(get_config_var('LDSHARED'))"

你应该发现不正确的 gcc 在配置的开头,例如:

/non/existent/path/gcc -pthread -shared

第一个解决方案

设置 LDSHARED 环境变量以用正确的 gcc 路径覆盖它:

export LDSHARED="/correct/path/to/gcc -pthread -shared"

然后重建扩展,它应该可以工作。

第二种解决方案(可能更好)

LDSHARED 配置是从构建时生成的 lib/python2.7/_sysconfigdata.py 文件中检索的。

您可以修改此文件,因此无需设置环境变量。


调试技巧

设置DISTUTILS_DEBUG环境激活调试模式,编译失败时可以看到traceback。