简体   繁体   English

cython导入错误在同一软件包中

[英]cython import error in same package

I've seen this question and the answer don't seems to be working. 我看过这个问题 ,答案似乎没有用。 Following is my directory structure. 以下是我的目录结构。

.
├── my_package
│   ├── a.pyx
│   ├── b.pyx
│   ├── b.pxd
│   ├── test.py
│   └── __init__.py
└── setup.py

a.pyx file a.pyx文件

cimport my_package.b  as b

class a:
    def __init__(self):
        self.b = b.b()
        self.b.run()

b.pyx file b.pyx文件

cdef class b:

    def __init__(self):
        pass

    cpdef run(self):
        print "b is running"

b.pxd file b.pxd文件

cdef class b:
    cpdef run(self)

test.py test.py

import a

c = a.a()

setup.py setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy

extensions = [
    Extension("my_package.a", ["my_package/a.pyx"]
        ),
    Extension("my_package.b", ["my_package/b.pyx"]
)
]

for e in extensions:
    e.cython_directives = {"embedsignature": True}

setup(
    name = "preprocess",
    ext_modules = cythonize(extensions),
)

after running python setup.py build_ext --inplace there is no compile error. 运行python setup.py build_ext --inplace之后,没有编译错误。 But if I try to run test.py it gives ImportError: No module named my_package.b . 但是,如果我尝试运行test.py,则会出现ImportError: No module named my_package.b

Any input will be appreciated. 任何输入将不胜感激。

BTW if we change the first line of a.pyx from cimport my_package.b as b to import b it will work. 顺便说一句,如果我们将a.pyx的第一行从cimport my_package.b as b import b ,它将起作用。

For cimport of a sub-package to work, the package directory needs to contain an __init__.pxd . 为了cimport子包的cimport起作用,包目录必须包含__init__.pxd

It is the equivalent of __init__.py for cimport instead of import . 对于cimport ,它相当于__init__.py ,而不是import

Make directory structure be like this: 使目录结构如下:

.
├── my_package
│   ├── a.pyx
│   ├── b.pyx
│   ├── b.pxd
│   ├── test.py
│   └── __init__.py
│   └── __init__.pxd
└── setup.py

Then include pxd files as package data in setup.py so that they get installed: 然后将pxd文件作为包数据包含在setup.py以便安装它们:

from setuptools import setup, Extension
from Cython.Build import cythonize

extensions = [
    Extension("my_package.a", ["my_package/a.pyx"]
        ),
    Extension("my_package.b", ["my_package/b.pyx"]
)
]

for e in extensions:
    e.cython_directives = {"embedsignature": True}

package_data = {'my_package': ['*.pxd']}

setup(
    name = "preprocess",
    ext_modules = cythonize(extensions),
    include_package_data=True,
    package_data=package_data,
)

Note - import numpy should not be in setup.py as it will make installing package not work unless numpy has already been installed. 注意import numpy不应位于setup.py中,因为除非已安装numpy,否则安装包将无法工作。

Put it in requirements.txt to have it installed along with the package. 将其放在requirements.txt以与软件包一起安装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM