在cython包中导入错误

时间:2017-09-13 09:58:51

标签: python python-2.7 cython

按照这些示例(https://github.com/cython/cython/wiki/PackageHierarchyhttps://groups.google.com/forum/#!msg/cython-users/6trL0V1bLx4/7bxhj0xCK50JCython: ImportError: No module named 'myModule': how to call a cython module containing a cimport to another cython nodule?),我创建了以下cython包设置:

test_outside.py
cython_pckg/
  __init__.py
  setup.py
  test_inside.py
  Code/
    __init__.py
    worker/
      __init__.py
      worker_1.pyx
      worker_1.pxd
      worker_2.pyx
      worker_2.pxd
      worker_3.pyx
      worker_3.pxd

我的setup.py文件如下所示:

from distutils.core import setup
from distutils.extension import Extension
import numpy
from Cython.Distutils import build_ext

ext_modules = [
   Extension("Code.worker.worker_1", ["Code/worker/worker_1.pyx"], include_dirs=[".", numpy.get_include()]),
   Extension("Code.worker.worker_2", ["Code/worker/worker_2.pyx"], include_dirs=["."]),
   Extension("Code.worker.worker_3", ["Code/worker/worker_3.pyx"], include_dirs=[".","./Code/worker/", numpy.get_include()])
]

setup(name="C_Extensions",
  cmdclass={"build_ext": build_ext},
  ext_modules=ext_modules,
  script_args=["build_ext"],
  options={'build_ext':{'inplace':True, 'force':True}}
)

请注意,worker_3导入worker_2。如果我尝试在test_inside.py中导入这些模块,一切正常。但是,将模块导入test_outside.py会为文件ImportError: No module named Code.worker.worker_2引发worker_3.pyx。在顶级__init__.py,我导入所有内容。

from Code.worker.worker_1 import *
from Code.worker.worker_2 import *
from Code.worker.worker_3 import *

我该如何使这项工作?

1 个答案:

答案 0 :(得分:1)

worker_3.pyx

cimport worker_2

注意 - cimport Code.<..>

Cython仅在使用.pxd时查看可用的cimport文件。

它不知道模块级别名称间距,这意味着在setup.py的Extension中定义了模块名称。

参考 - Cython docs