如何在Cython中指定`.pxd`文件的路径

eth*_*oks 5 cython include-path

我的项目具有以下目录结构:

.
??? Makefile
??? pxd
??? pyx
?   ??? Landscaping.pyx
?   ??? Shrubbing.pxd
?   ??? Shrubbing.pyx
??? setup.py
Run Code Online (Sandbox Code Playgroud)

但是,如果我移到Shrubbing.pxd其他任何地方,例如pxd/,我将收到以下错误:

Error compiling Cython file:
------------------------------------------------------------
...
import pyx.Shrubbing
cimport Shrubbing
       ^
------------------------------------------------------------

pyx/Landscaping.pyx:2:8: 'Shrubbing.pxd' not found

Error compiling Cython file:
------------------------------------------------------------
...
import pyx.Shrubbing
cimport Shrubbing

cdef Shrubbing.Shrubbery sh
    ^
------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为setup.py我有:

from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules=cythonize([
    Extension(
        'pyx.Landscaping',
        sources=["pyx/Landscaping.pyx"],
        include_dirs=['pxd']), # <-- HERE
    Extension('pyx.Shrubbing', sources=["pyx/Shrubbing.pyx"])
]))
Run Code Online (Sandbox Code Playgroud)

明确指定的新目录Shrubbing.pxd

源文件都很短,但是为了避免使这篇文章混乱,我将只发布一个到存储库的链接:https : //github.com/lobachevzky/landscaping

谢谢你的帮助。

dan*_*nny 5

include_dirs适用于 C/C++ 标头,而不是 Cythonpxd文件。

一般来说,最好将相关pyx/pxd文件放在同一目录中,即Shrubbing.pyx和Shrubbing.pxd应位于同一目录中。

然后,要从其他模块中使用它,请通过扩展中使用的名称包含__init__.pxd和,例如,就像使用 Python 模块一样。cimportpyx.Shrubbing

如果在 python 中导入(不是cimport),__init__.py也应该包含在内。

当在同一个模块中使用时,OTOH,.pxd需要在该模块的运行时可用,这意味着将其包含在Python搜索路径中。

如果要将 pxd 文件组织到单独的目录中,请在模块目录中以符号方式链接它们,以使它们可供模块使用,该目录包含一个__init__.pxd.py文件。

这有点混乱,因为 Cython 目前不支持相对导入,因此当想要从另一个目录导入时需要链接。

请参阅文档了解更多详细信息