通过Cython编译Python包

时间:2017-02-14 13:23:02

标签: python cython importerror python-packaging cythonize

我是cython的新手,有没有人知道如何通过Cython编译python项目(开销相对较低),因为我不断收到以下导入错误:

  

ImportError:没有名为CythonRelated.testSource.MyClassObject

的模块

我的测试项目结构是这样的:

CythonRelated/
           setup.py
           testSource/
                  MainCythonTest.py
                  MyClassObject.py
                  MainCythonTest.pyx   
                  MyClassObject.pyx

MainCythonTest从MyClassObject模块导入类的地方(通过

from CythonRelated.testSource.MyClassObject import myCustomObj

),初始化一个对象并调用一个对象方法。

我的setup.py看起来像这样:

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

setup(
    name = "My cython test app",
    ext_modules = cythonize("testSource/*.pyx", include_path = ["."]),
    packages = ["CythonRelated", "CythonRelated.testSource"]
)

我错过了什么?

在CythonRelated之外使用setup.py(显然在cythonize中更新* .pyx文件的相应路径)也没有帮助

  

MyClassObject.py

import sys
print sys.version_info

class myCustomObj():
    def __init__(self, value):
        self.value_ = value

    def classInfo(self):
        print "calling class {0} object with value of  {1}".format(self.__class__.__name__,
                                                                  self.value_)
  

MainCythonTest.py

import pyximport; pyximport.install()

from CythonRelated.testSource.MyClassObject import myCustomObj

def myFunc():

    aObj = myCustomObj(12)

    bObj = myCustomObj(21)

    bObj.classInfo()

    aObj.classInfo()

    print "myFunc called"

myFunc()

1 个答案:

答案 0 :(得分:0)

无论如何,您需要移动setup.py文件,因为它不能成为“编译”项目的一部分。

然后,主要问题是__init__.pyCythonRelated中缺少CythonRelated/testSource个文件。如果没有此文件,则该目录不是可导入的Python模块。通过这两项更改,我可以pip install --user -e .打包并运行程序MainCythonTest.py