简而言之
我尝试编译一个名为extension2
的 cython 扩展,该扩展从自创建包中导入文件extension
。构建extension2
时,我收到错误,尽管该文件正好位于分隔路径上,但找不到extension.pxd
。
详
我正在构建两个涉及cython的软件包,一个软件包A
和一个依赖于A
的软件包B
。A
是命名空间包nsp
的子包。也就是说,文件夹结构如下所示:
├── nsp
│ └── A
| ├── extension.pxd
| ├── extension.pyx
│ └── __init__.py
└── setup.py
这里,setup.py
如下:
from setuptools import setup
from setuptools.extension import Extension
# factory function
def my_build_ext(pars):
# import delayed:
from setuptools.command.build_ext import build_ext as _build_ext
# include_dirs adjusted:
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include())
#object returned:
return build_ext(pars)
extensions = [Extension(nsp.A.extension, ['nsp/A/extension.cpp'])]
setup(
cmdclass={'build_ext' : my_build_ext},
setup_requires=['numpy'],
install_requires=['numpy'],
packages=['nsp.A'],
ext_modules=extensions
package_data={
'nsp/A': ['*.pxd', '*.pyx']
},
)
安装文件的灵感来自 add-numpy-get-include-argument-to-setuptools-without-preinstall-numpy 和 distributing-cython-modules。cython文件已经成功地转换为具有另一个脚本的.cpp
文件。
我安装软件包A
pip install .
在setup.py
的目录中.一切都按预期工作,我可以在...Anaconda3Libsite-packagesnspA
下找到包的所有文件,包括*.pxd
文件。
现在,我寻求为extension2
创建一个*.cpp
文件,以便稍后将其打包到第二个包B
中。extension2.pxd
读取的文件
from nsp.A.extension cimport mymethod
用于创建*.cpp
文件的脚本读取
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy as np
import sys
print(sys.executable)
NAME = 'extension2'
extensions = [Extension(NAME, [NAME+'.pyx'],
include_dirs=[np.get_include()]
)
]
setup(name=NAME,
ext_modules = cythonize(extensions, language="c++",
compiler_directives=compiler_directives),
include_dirs=[np.get_include()]
)
当我使用python myscript build_ext --inplace
运行此脚本时,我收到一个错误,指示缺少pxd
文件:
from nsp.A.extension cimport mymethod
^
------------------------------------------------------------
.extension2.pxd:11:0: 'nspAextension.pxd' not found
但是,此文件正好存在。(sys.executable
是包含已安装软件包的Anaconda3
文件夹(如何解决此问题?
附加信息
我在Windows x64上使用python 3.7
Cython目前还不支持隐式命名空间包。也就是说,cython只搜索包含文件init.*
的子目录,其中*
可以是py
、pyc
、pyx
和pxd
中的任何内容。
我已经为此问题创建了一个错误跟踪器报告,以防您想跟进该问题是否已在较新版本中修复(我使用 Cython 0.29.14(。
在此之前,解决方法是在文件夹nsp
中创建空文件__init__.pxd
。python应该忽略这个文件,因为它不是一个*.py
文件,并允许cython在子目录中搜索包。然后,文件结构如下所示:
├── nsp
│ ├── __init__.pxd
│ └── A
| ├── extension.pxd
| ├── extension.pyx
│ └── __init__.py
└── setup.py
若要在命名空间包中安装其他文件__init__.pxd
,请将setup(...)
的packages
参数更改为packages=['nsp', 'nsp.A']
,将package_data
参数更改为package_data={'': ['*.pxd', '*.pyx']}
。
编辑:
该错误已被cython开发人员所知,并将在版本3中修复。请参阅修复从 PEP420 命名空间导入。