使用pyximport在python中导入cython文件会导致ImportError ::因为distutils.error.CompilerError

问题描述

我从https://github.com/scikit-learn/scikit-learn分叉了scikit-learn github代码。我要调试此文件https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py

添加

from sklearn.datasets.samples_generator import make_blobs
bandwidth=0.5
num_mean_shift_iterations=5
num_points=100
centers = [[-1,-1],[-1,1],[1,1]]
x1,y = make_blobs(n_samples=num_points,centers=centers,cluster_std=0.4,random_state=42)
clustering = MeanShift(bandwidth=bandwidth,n_jobs = -1,max_iter=num_mean_shift_iterations).fit(x1)
_mean_shift.py中的

。而且我正在使用安装了Python 3.7的Sypder环境运行它。

以下是完全错误

ImportError: Building module utils.murmurhash Failed ["distutils.errors.CompileError:command 'C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\2019\\\\Community\\\\VC\\\\Tools\\\\MSVC\\\\14.24.28314\\\\bin\\\\HostX86\\\\x64\\\\cl.exe' Failed with exit status 2\n"]

其中utils.murmurhash是我要导入位于不同位置的python文件中的内容

我使用https://pystan.readthedocs.io/en/latest/windows/在python中创建了一个新环境,即安装了此网页上列出的所有库。

包含以下代码

distutils.cfg位于: C:\ Users \ username \ Anaconda3 \ envs \ stan_env \ Lib \ distutils \ distutils.cfg

[build]
compiler=mingw32

[build_ext]
compiler = mingw32

我用过:

import pyximport
pyximport.install() 
在导入cython_files之前,在python文件

请指出错误。谢谢。

解决方法

据我所知,您正在使用:

import pyximport
pyximport.install() 

编译Cython以便导入* .pyx文件。

site上写为: “如果您的模块不需要不需要任何额外的C库或特殊的构建设置,则可以使用pyximport模块”

这可能会导致问题,因为sklearn导入了许多C库。

要首先导入* .pyx,必须通过运行以下命令进行编译:

# change directory to forked project ([example-how-to-do-that][2])
# only for Windows users with anaconda:
conda activate {environment_name} # the same name which you provided during environment creation
# only for linux users who don't use anaconda:
# source {environment_name}/bin/activate
python setup.py build_ext --inplace

在终端中。

当我尝试直接在代码中编译cython模块时也遇到了问题(通过pyximport包)。我无法导入它们。就我而言,它也是sklearn的文件。终端编译Cython的方法对我有帮助。