如何在setup.py中使用cythonize编译.pyx

时间:2016-06-10 07:57:08

标签: python python-2.7 cython

给定目录结构:

projectroot/
    docs/
    project/
        __init__.py
        core/
            __init__.py
            another.pyx
            anotherone.pyx
            lib/
                __init__.py
                something.pyx
    tests/
        mytest.py
    setup.py

setup.py包含以下内容:

from Cython.Build import cythonize

try:
    from setuptools import Extension, setup, find_packages
except ImportError:
    from distutils.core import Extension, setup, find_packages

if __name__ == '__main__':
    setup(
        name='myproject',
        version='1.0.0',
        packages=find_packages(),
        ext_modules=cythonize([
             Extension('*', ['project/core/lib/*.pyx']),
             Extension('*', ['project/core/*.pyx'])
        ])
    )

它正确编译。唯一的问题是,当我从root directory打开python解释器时,它会引发ImportError

(test) [root@mico projectroot]# python
>>> from project.core.lib.another import AnotherClass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named another

但是当我在任何其他目录中打开解释器时,它可以工作。

(test) [root@mico projectroot/project]# python
>>> from project.core.lib.another import AnotherClass
# no error

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

当你在根目录中时,python首先尝试从本地路径导入,即它在项目/核心内部进行查看。

我认为您可能全局安装了这个包(在/usr/lib/pythonx.y/dist-packages中),因此除了在根目录中之外它将在任何地方工作,因为。project/core中不会出现.so。

对于任何其他当前目录,python将从/usr/lib/pythonx.y/dist-packages中安装它的全局文件夹中获取.so。 要在本地使用它,您需要在Nils Werner提到的根目录中执行python setup.py build_ext --inplacepip install -e .

相关问题