用Cython编译Python包

2024-09-30 01:26:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我对cython相当陌生,有人知道如何通过cython编译python项目吗(开销相对较低),因为我一直收到以下导入错误:

ImportError: No module named CythonRelated.testSource.MyClassObject

我的测试项目结构如下:

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

其中MainCythonTest从MyClassObject模块导入类(通过

from CythonRelated.testSource.MyClassObject import myCustomObj

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

我的设置.py看起来像这样:

^{pr2}$

我错过了什么?在

接受设置.py在CythonRelated之外(显然更新了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()

Tags: pyimportselfvaluedefmyfuncclassprint
1条回答
网友
1楼 · 发布于 2024-09-30 01:26:00

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

然后,主要问题是CythonRelated和{}中缺少__init__.py文件。没有这个文件,目录就不是一个可导入的Python模块。有了这两个更改,我可以pip install user -e .包并运行程序MainCythonTest.py

相关问题 更多 >

    热门问题