ems*_*sch 6 python compiler-errors cython python-3.x cimport
我正在尝试在 cython 中使用显式相对导入。从发行说明看来,相对导入应该在 cython 0.23 之后工作,而我将 0.23.4 与 python 3.5 一起使用。但是我收到了这个奇怪的错误,我找不到很多引用。错误仅来自 cimport:
driver.pyx:4:0: relative cimport beyond main package is not allowed
Run Code Online (Sandbox Code Playgroud)
目录结构为:
myProject/
setup.py
__init__.py
test/
driver.pyx
other.pyx
other.pxd
Run Code Online (Sandbox Code Playgroud)
看起来我可能在 setup.py 中搞砸了,所以我包含了下面的所有文件。
setup.py
driver.pyx:4:0: relative cimport beyond main package is not allowed
Run Code Online (Sandbox Code Playgroud)
driver.pyx
#!/usr/bin/env python
from . import other
from . cimport other
Run Code Online (Sandbox Code Playgroud)
other.pyx
#!/usr/bin/env python
HI = "Hello"
cdef class Other:
def __init__(self):
self.name = "Test"
cdef get_name(self):
return self.name
Run Code Online (Sandbox Code Playgroud)
other.pxd
cdef class Other:
cdef get_name(self)
Run Code Online (Sandbox Code Playgroud)
我已经试过移动__init__.py到test/。我试过setup.py在test目录中运行(include_dirs适当调整)。他们都给出了同样的错误。
如果我这样做cimport other并删除.它,它可以工作,但这是一个玩具示例,我需要相对导入,以便其他文件夹可以正确导入。这是我能为这个错误找到的唯一例子,我非常有信心我的问题是不同的。
我能找到的关于此错误的唯一其他示例是machinekit 项目的hal.pyx中。我非常有信心这是一个不同的错误,但今天我意识到,在解决该错误后,machinekit 正在工作,这意味着显式相对导入必须有效。他们的文件指的是不在目录树中的文件,但我猜是在编译时的某个时刻创建的。重要的是,它包括父目录而不是子目录。setup.pylinuxcncinclude_dirs
转换为我的项目结构,这意味着我放入myProject而include_dirs不是test/. 在第二次阅读本指南后,我终于开始了解一点 python 是如何看待包的。问题是它include_dirs是子目录。看起来这有效地使 cython 将其视为单个平面目录,在这种情况下不允许相对导入?像这样的错误可能会让事情变得更清楚:
ValueError: Attempted relative import in non-package
Run Code Online (Sandbox Code Playgroud)
我仍然没有足够深入的理解来确切地知道发生了什么,但幸运的是解决方案相对简单。我刚刚更改了include_dirs使 cython 识别嵌套文件结构:
from setuptools import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension('other', ['test/other.pyx'],),
Extension('driver', ['test/driver.pyx'],),
]
setup(
name='Test',
ext_modules=ext_modules,
include_dirs=["."],
cmdclass={'build_ext': build_ext},
)
Run Code Online (Sandbox Code Playgroud)
现在一切正常了!
| 归档时间: |
|
| 查看次数: |
2070 次 |
| 最近记录: |