使用 cython 扩展打包 python

Packaging python with cython extension

我正在尝试构建一个同时使用 python 和 cython 模块的包。我遇到的问题是在构建和安装之后处理导入,我不确定如何从构建过程生成的 .so 文件中导入文件。

在构建我的文件夹结构之前是这样的

root/
├── c_integrate.c
├── c_integrate.pyx
├── cython_builder.py
├── __init__.py
├── integrator_class.py
├── integrator_modules
│   ├── cython_integrator.py
│   ├── __init__.py
│   ├── integrator.py
│   ├── numba_integrator.py
│   ├── numpy_integrator.py
│   ├── quadratic_error.png
│   ├── report3.txt
│   ├── report4.txt
│   └── report5.txt
├── report6.txt
├── setup.py
└── test
    ├── __init__.py
    └── test_integrator.py

使用 python3.5 setup.py build 构建会在 root

中提供此新文件夹
root/build/
├── lib.linux-x86_64-3.5
│   ├── c_integrate.cpython-35m-x86_64-linux-gnu.so
│   ├── integrator_modules
│   │   ├── cython_integrator.py
│   │   ├── __init__.py
│   │   ├── integrator.py
│   │   ├── numba_integrator.py
│   │   └── numpy_integrator.py
│   └── test
│       ├── __init__.py
│       └── test_integrator.py

setup.py 文件看起来像这样

from setuptools import setup, Extension, find_packages
import numpy

setup(
    name = "integrator_package",
    author = "foo",
    packages = find_packages(),
    ext_modules = [Extension("c_integrate", ["c_integrate.c"])],
    include_dirs=[numpy.get_include()],
)

我的问题是:如何将函数的导入语句从 .so 文件写入 rootcython_integrator 和 [=22= 中的 ìntegrator_class.py ] 位于 build 目录中。附加到 sys.path 似乎是一个我不太喜欢的快速而肮脏的解决方案。

编辑: 正如评论中指出的那样,我还没有安装该软件包。这是因为我不知道写什么.so文件中导入

无特定顺序:

  1. 文件 setup.py 通常位于项目根目录下方。示例:

    library_name/
        __init__.py
        file1.py
    setup.py
    README
    
  2. 然后,构建目录出现在项目源代码的旁边,而不是项目源代码中。

  3. 要在Python中导入文件c_integrate.cpython-35m-x86_64-linux-gnu.so,只需导入"c_integrate"。其余的命名是自动处理的,因为它只是平台信息。参见 PEP 3149

  4. 有效模块是

    之一
    1. 一个包含 modulename/__init__.py 个文件的目录
    2. 一个名为 modulename.py
    3. 的文件
    4. 一个名为 modulename.PLATFORMINFO.so
    5. 的文件

    当然位于Python路径中。因此,编译的 Cython 模块不需要 __init__.py 文件。

    根据您的情况,将 Cython 代码移动到 项目目录中,然后执行相对导入 import .c_integrate 或完整的 from integrator_modules import c_integrate,其中后者仅当你的包 installed.

  5. 时有效

可以在我关于 Cython 模块的博客 post 中找到其中一些信息 http://pdebuyl.be/blog/2017/cython-module.html

我相信这应该能让你构建一个合适的包,如果没有,请在下面评论。

编辑:要完成配置(请参阅下面的评论),poster also

  1. 修复了 setup.py 文件中的模块路径,使其成为从 PYTHONPATH 开始的完整模块名称:Extension("integrator_package.integrator_modules.c_integrat‌​or", ["integrator_package/integrator_modules/c_integrator.c"] 而不是 Extension("c_integrate", ["c_integrate.c"])]
  2. Cythonize 模块,构建它并使用相同的 Python 解释器。

进一步评论:setup.py 文件也可以对文件进行 cythonize 处理。包含 .pyx 文件而不是 .c 文件作为源文件。

cythonize(Extension('integrator_package.integrator_modules.c_integrat‌​or',
          ["integrator_package/integrator_modules/c_integrator.pyx"],
          include_dirs=[numpy.get_include()]))