我有以下目录结构:
testcython/
setup.py
testcython/
__init__.py
foo.pyx
stuff.py
bar/
__init__.pxd
__init__.py
bar.pxd
bar.pyx
其中文件内容如下:
bar.pxd
# cython: language_level=3
cdef int square(int x)
bar.pyx
# cython: language_level=3
cdef int square(int x):
return x * x
foo.pyx
# cython: language_level=3
import cython
cimport numpy as np
import numpy as np
from .Bar cimport square
def do_square(x):
return square(x)
stuff.py
from __future__ import print_function
from .Foo import do_square
def do():
print(do_square(2))
setup.py
import os, sys
from Cython.Build import build_ext, cythonize
from setuptools import setup, Extension, find_packages
def ext_modules():
import numpy as np
include_dirs = ['.', np.get_include()]
root_dir = os.path.abspath(os.path.dirname(__file__))
bar_ext = Extension(
"Bar",
sources=[root_dir + "/testcython/bar/bar.pyx"],
include_dirs=include_dirs,
)
foo_ext = Extension(
"Foo",
sources=[root_dir + "/testcython/foo.pyx"],
include_dirs=include_dirs
)
exts = [bar_ext, foo_ext]
return cythonize(exts)
REQUIREMENTS = [
"numpy",
"cython"
]
setup(
name="testcython",
packages=find_packages(),
ext_package="testcython",
ext_modules=ext_modules(),
cmdclass={"build_ext" : build_ext},
zip_safe=False,
install_requires=REQUIREMENTS
)
问题
问题是,当我尝试安装它(pip install -e .
在顶级testcython
目录中)时,我从 Cython 收到以下错误:
Complete output from command python setup.py egg_info:
Error compiling Cython file:
------------------------------------------------------------
...
import cython
cimport numpy as np
import numpy as np
from .Bar cimport square
^
------------------------------------------------------------
testcython/foo.pyx:7:0: relative cimport beyond main package is not allowed
Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
from .Bar cimport square
def do_square(x):
return square(x)
^
------------------------------------------------------------
这个答案(cython: relative cimport beyond main package is not allowed)意味着在对象的参数中包含根目录( '.'
)应该可以解决问题。include_dirs
Extension
虽然Cython 文档的这一部分提到在使用包时zip_safe=False
的参数中使用。setup
setuptools
正如您从我setup.py
上面的文件中看到的那样,我已经包含了这两个 - 但我仍然收到上面的错误。
注意:如果我将扩展名(在Extension
构造函数中)分别从Bar
和Foo
更改为testcython.Bar
和testcython.Foo
,那么我会得到一个不同的错误:
Complete output from command python setup.py egg_info:
Error compiling Cython file:
------------------------------------------------------------
...
import cython
cimport numpy as np
import numpy as np
from .Bar cimport square
^
------------------------------------------------------------
testcython/foo.pyx:7:0: 'testcython/Bar/square.pxd' not found
Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
from .Bar cimport square
def do_square(x):
return square(x)
^
------------------------------------------------------------