简体   繁体   English

Python包Cython模块

[英]Python package Cython module

I have the following package structure: 我有以下包结构:

+ repo/
+ setup.py
+ package/
    + module1/
        + submodule1.py
        + submodule2.pyx
    + module2/
        + submodule3.py

I would like to use submodule2.pyx from submodule1.py by something like: 我想通过类似以下方式使用submodule1.py中的submodule2.pyx:

import submodule2

but I have absolutely no idea how to do this. 但是我绝对不知道该怎么做。 I tried adding the following lines to my setup.py: 我尝试将以下几行添加到我的setup.py中:

from distutils.core import setup
from setuptools import setup
from Cython.Distutils import build_ext

ext_modules = cythonize(Extension(
        "zindex",
        sources=["ndmg/graph/zindex.pyx"],
        language="c",
))
for e in ext_modules:
    e.pyrex_directives = {"boundscheck": False}

setup(
    name='ndmg',
    ext_modules = ext_modules,
    packages=[
        'package',
        'package.module1',
    ....
)

but was unsuccessful. 但没有成功。 All of the tutorials I could find had very very simplified examples, so I am not sure how to include Cython modules in my python package when the rest of the package is all just normal python code. 我可以找到的所有教程都具有非常简化的示例,因此当该包的其余部分只是普通的python代码时,我不确定如何在我的python包中包括Cython模块。 Does anybody have any good examples I could follow, or can somebody tell me what I'm doing wrong? 有人能效法我吗?或者有人可以告诉我我做错了什么?

Thanks in advance! 提前致谢!

The name given to cythonize is what Cython will use to call the module and what it will be have to be imported as. cythonize的名称是Cython用来调用该模块的名称,以及将其导入为的名称。

The above setup.py will generate a native extension called zindex and will have to be imported as import zindex even within python files in the zindex package . 上面的setup.py将生成一个名为zindex的本机扩展, 即使在zindex包中的python文件中 ,也必须将其作为import zindex

Here is an example of how to do this: 这是如何执行此操作的示例:

from distutils.core import setup
from setuptools import setup
from Cython.Distutils import build_ext

ext_modules = cythonize(Extension(
        "ndmg.graph.zindex",
        sources=["ndmg/graph/zindex.pyx"],
        language="c",
))
<..>

Build and install extension. 生成并安装扩展程序。

In a python file under ndmg/graph/py_index.py you can then do. 然后可以在ndmg / graph / py_index.py下的python文件中执行操作。

from zindex import <..>

to import from the cython module. 从cython模块导入。

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

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