python - cython:不允许超出主包的相对 cimport

标签 python python-3.x compiler-errors cython cimport

我正在尝试在 cython 中使用显式相对导入。来自release notes似乎相对导入应该在 cython 0.23 之后工作,我正在使用 0.23.4 和 python 3.5。但是我遇到了这个奇怪的错误,我找不到很多引用资料。错误仅来自 cimport:

driver.pyx:4:0: relative cimport beyond main package is not allowed

目录结构为:

    myProject/
        setup.py
        __init__.py
        test/
            driver.pyx
            other.pyx
            other.pxd

看来我可能在 setup.py 中搞砸了,所以我包含了下面的所有文件。

setup.py

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=["test/"],
    cmdclass={'build_ext': build_ext},
)

驱动.pyx

#!/usr/bin/env python
from . import other
from . cimport other

other.pyx

#!/usr/bin/env python

HI = "Hello"

cdef class Other:
    def __init__(self):
        self.name = "Test"

    cdef get_name(self):
        return self.name

other.pxd

cdef class Other:
    cdef get_name(self)

我试过将 __init__.py 移动到 test/ 中。我尝试在 test 目录中运行 setup.py(适当调整 include_dirs)。他们都给出了相同的错误。

如果我执行 cimport other 并删除 . 它可以工作,但这是一个玩具示例,我需要相对导入以便其他文件夹可以正确导入。这是唯一的 example我可以找到此错误,而且我非常有信心我的问题有所不同。

最佳答案

唯一的其他example我发现这个错误在 hal.pyx 中的 machinekit project .我非常有信心这是一个不同的错误,但今天我意识到在解决该错误后,machinekit 正在工作,这意味着显式相对导入必须工作。他们的 setup.py 文件引用了 linuxcnc,它不在目录树中,但我猜它是在编译期间的某个时刻创建的。重要的是 include_dirs 包括父目录而不是子目录。

转换为我的项目结构意味着我将 myProject 放在 include_dirs 而不是 test/ 中。看完这篇guide我第二次终于开始了解 python 如何看待包。问题是 include_dirs 是子目录。似乎这有效地使 cython 将其视为单个平面目录,在这种情况下不允许相对导入?像这样的错误可能使它更清楚:

ValueError: Attempted relative import in non-package

我仍然没有足够深刻的理解来确切知道发生了什么,但幸运的是解决方案相对简单。我只是更改了 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},
)

现在一切正常!

关于python - cython:不允许超出主包的相对 cimport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555927/

相关文章:

python - 在 Python3 中对包含字典的列表进行排序

python - 获取python列表的所有k个组合的有效方法

c++ - 为什么在定义变量并链接库时为 "undefined reference"?

compiler-errors - LLVM教程OCaml编译错误

python - 使用 python 根据条件对绘图进行颜色填充

python - 使用python将rtf转换为pdf

python - mFailed 解析文本文件

python - Json 文件中的列表框

python3和pywin32关闭excel

c++ - std::inner_product 计算 vector 的标准差