如何使用 cython 编译和链接多个 python 模块(或包)? [英] How to compile and link multiple python modules (or packages) using cython?

查看:49
本文介绍了如何使用 cython 编译和链接多个 python 模块(或包)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 python 模块(组织成包),它们相互依赖.例如

I have several python modules (organized into packages), which depend on each other. e.g.

  • 模块 1
  • 模块 2:导入模块 1
  • 模块 3
  • 模块 4:导入模块 3、模块 2、模块 1

假设开发应用程序的相关接口在 Module4 中,我想使用 cython 生成 Module4.so.如果我以天真的方式继续,我会得到一个扩展模块4.so,我可以导入该扩展依赖于模块1、模块2、模块3的python源代码.

Let's assume the relevant interface to develop applications is in Module4 and I want to generate a Module4.so using cython. If I proceed in the naive way, I get an extension Module4.so which I can import BUT the extension relies on the python source code of Module1, Module2, Module3.

是否有一种编译方法可以使 Module1、Module2、Module3 编译并链接到 Module4?我想避免手动操作,例如先编译Module1.so,然后修改Module2中的import声明,导入Module1.so而不是Module1.py,然后将Module2编译成Module2.so,以此类推..

Is there a way to compile so that also Module1,Module2, Module3 are compiled and linked to Module4? I would like to avoid doing everything manually, e.g. first compile Module1.so then change import declaration in Module2, so as to import Module1.so rather than Module1.py, then compile Module2 into Module2.so and so on....

推荐答案

编辑.前两个选项是指 Cython 的具体代码,我错过的是关于纯 python 模块的问题,所以选项 3 是解决方案.

Edit. First two options refer to Cython's specific code, what I've missed is that the question is about pure python modules, so option 3 is the solution.

有几个选项:

1.请参阅如何在包中创建模块层次结构":https://github.com/cython/cython/wiki/PackageHierarchy

1. See this "How To Create A Hierarchy Of Modules In A Package": https://github.com/cython/cython/wiki/PackageHierarchy

2.我更喜欢包含"语句:http://docs.cython.org/src/userguide/language_basics.html#the-include-statement我有很多 .pyx 文件,它们都包含在 main.pyx 中,它们都在一个命名空间中.结果是一个大模块:http://code.google.com/p/cefpython/source/browse/cefpython.pyx

2. I prefer the "include" statement: http://docs.cython.org/src/userguide/language_basics.html#the-include-statement I have many .pyx files and they are all included in main.pyx, it's all in one namespace. The result is one big module: http://code.google.com/p/cefpython/source/browse/cefpython.pyx

3.您可以通过添加多个扩展"使用 setup 一次性编译所有模块:

3. You can compile all your modules at once using setup by adding more than one "Extension":

setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("example", sourcefiles), Extension("example2", sourcefiles2), Extension("example3", sourcefiles3)]
)

4.更高效的编译 - 请参阅此处.

4. A more efficent compilation - see here.

setup (
    name = 'MyProject',
    ext_modules = cythonize(["*.pyx"]),
)

这篇关于如何使用 cython 编译和链接多个 python 模块(或包)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆