嵌套的Python C扩展/模块? [英] Nested Python C Extensions/Modules?

查看:131
本文介绍了嵌套的Python C扩展/模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编译一个C-Python模块,使其在另一个模块中是本地的?例如.如果我有一个名为"bar"的模块和另一个名为"mymodule"的模块,如何编译"bar"以便通过"import mymodule.bar"导入?

How do I compile a C-Python module such that it is local to another? E.g. if I have a module named "bar" and another module named "mymodule", how do I compile "bar" so that it imported via "import mymodule.bar"?

(很抱歉,如果措辞不好,我不确定它的正确用语是什么.)

(Sorry if this is poorly phrased, I wasn't sure what the proper term for it was.)

我在setup.py中尝试了以下操作,但似乎不起作用:

I tried the following in setup.py, but it doesn't seem to work:

from distutils.core import setup, Extension

setup(name='mymodule',
      version='1.0',
      author='Me',
      ext_modules=[Extension('mymodule', ['mymodule-module.c']),
                   Extension('bar', ['bar-module.c'])])

修改

谢谢亚历克斯.所以这就是我最终使用的:

Thanks Alex. So this is what I ended up using:

from distutils.core import setup, Extension

PACKAGE_NAME = 'mymodule'

setup(name=PACKAGE_NAME,
      version='1.0',
      author='Me',
      packages=[PACKAGE_NAME],
      ext_package=PACKAGE_NAME
      ext_modules=[Extension('foo', ['mymodule-foo-module.c']),
                   Extension('bar', ['mymodule-bar-module.c'])])

当然有一个名为"mymodule"的文件夹,其中包含__init__.py.

with of course a folder named "mymodule" containing __init__.py.

推荐答案

说明是此处:

扩展名('foo',['src/foo1.c', 'src/foo2.c'])

Extension('foo', ['src/foo1.c', 'src/foo2.c'])

描述存在于其中的扩展 根包,而

describes an extension that lives in the root package, while

扩展名('pkg.foo',['src/foo1.c', 'src/foo2.c'])

Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

在 pkg包装.源文件和 产生的目标代码在以下方面是相同的 两种情况;唯一的区别是 文件系统中的哪个位置(因此 在Python的命名空间层次结构中的何处 由此产生的扩展寿命.

describes the same extension in the pkg package. The source files and resulting object code are identical in both cases; the only difference is where in the filesystem (and therefore where in Python’s namespace hierarchy) the resulting extension lives.

请记住,包始终是包含模块__init__的目录(或zipfile).要创建作为包主体的模块,该模块将被称为__init__并位于包的目录(或zipfile)下.我从来没有在C中做到这一点;如果无法直接执行此操作,请将该模块命名为_init,然后在__init__.py中执行from _init import *(from ... import *的少数合法使用之一;-).

Remember, a package is always a directory (or zipfile) containing a module __init__. To create a module that's a package body, that module will be called __init__ and live under the package's directory (or zipfile). I've never done that in C; if it doesn't work to do it directly, name the module e.g. _init instead, and in __init__.py do from _init import * (one of the very few legitimate uses of from ... import *;-).

这篇关于嵌套的Python C扩展/模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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