【问题标题】:Importing cython file in python, using pyximport results in the ImportError: because of distutils.error.CompilerError在python中导入cython文件,使用pyximport导致ImportError:因为distutils.error.CompilerError
【发布时间】:2020-09-22 07:37:46
【问题描述】:

我已经从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], [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 文件中导入的内容。

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

包含以下代码的distutils.cfg 位于: C:\Users\用户名\Anaconda3\envs\stan_env\Lib\distutils\distutils.cfg

[build]
compiler=mingw32

[build_ext]
compiler = mingw32

我用过:

import pyximport
pyximport.install() 

在导入 cython_files 之前的 python 文件中。

请指出错误。谢谢。

【问题讨论】:

  • 这个问题缺少minimal reproducible example,没有它就不可能知道出了什么问题。
  • @ead 我已将这些步骤添加到最小可重现示例中。请调查问题。谢谢。
  • 1) 必须有更多关于打印到 stderr 的错误的信息 2) 目前还不清楚您要对哪些文件进行 cythonize/编译。 3) 为什么要重新编译 murmurhash?
  • 我只是在运行文件:github.com/scikit-learn/scikit-learn/blob/master/sklearn/…,并进行了上述更改。该文件中使用的一个函数是在 murmurhash 中实现的。 murmurhash 是通过功能调用进行 cython 化的 cython 文件。
  • 如果文件是在我尝试使用的python文件中导入的,如何避免重新编译?

标签: python mingw cython importerror distutils


【解决方案1】:

我看到你正在使用:

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 的方法帮助了我。

【讨论】:

    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2012-10-16
    相关资源
    最近更新 更多