【问题标题】:Cython with `cimport numpy` fails带有“cimport numpy”的 Cython 失败
【发布时间】:2017-11-24 14:10:22
【问题描述】:

类似的问题已经被问过很多次了,但不幸的是,我再次遇到了将 Cython 与 Numpy 一起使用的问题。以这个最小的例子(它几乎遵循例子here):

# file test.pyx
import numpy as np
#cimport numpy as np

def func():
    print("hello")

我尝试使用的构建:

from distutils.core import setup
from Cython.Build import cythonize
import numpy as np
import os

os.environ["CC"] = "g++-7"

setup(
    ext_modules = cythonize("test.pyx", include_path = [np.get_include()])
)

此示例有效 (python setup.py build_ext --inplace),直到我取消注释 cimport ... 行,之后我得到众所周知的错误:

致命错误:numpy/arrayobject.h:没有这样的文件或目录

np.get_include() 返回的路径确实有arrayobject.h 标头,但在实际执行的g++ 命令中,包含目录缺少-I/...

g++-7 -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I /usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/include/python3 .6m -c test.c -o build/temp.macosx-10.11-x86_64-3.6/test.o

知道什么可能导致这个问题吗?

我在 Mac OS 上使用 Python 3.6.1,所有东西(Cython、Numpy、..)都使用 pip3 和 Cython 0.25.2 安装。

【问题讨论】:

  • 你可以试试:ext_modules = cythonize((Extension("test", sources=["test.pyx"], include_dirs=[np.get_include()], ), ))
  • 另外,cython 的版本是多少? cython3 --version
  • 皮埃尔,这太神奇了!它有效,虽然我不知道为什么/如何(还)

标签: python python-3.x numpy cython


【解决方案1】:

我的解决方法:

os.environ["C_INCLUDE_PATH"] = np.get_include()
setup(
    ext_modules = cythonize("test.pyx")
)

【讨论】:

    【解决方案2】:

    不要使用简单的 cythonize 命令,而是使用

    ext_modules = cythonize((Extension("test", sources=["test.pyx"], include_dirs=[np.get_include()], ), ))
    

    include_dirs 选项在此处提供给“扩展”,而不是将 include_path 与“cythonize”一起使用。

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多