如何打包 Python C 扩展,使其成为普通 Python 模块的子模块? [英] How to package a Python C Extension such that it is a submodule of a normal Python module?

查看:59
本文介绍了如何打包 Python C 扩展,使其成为普通 Python 模块的子模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个包含两部分的 python 库:

I wrote a python library with two parts:

  1. Python C 扩展
  2. Python C 扩展的 Python 包装器

我希望能够以这样的方式打包它,即 Python 包装器是顶级模块 foo 而 Python C 扩展是位于 foo._foo<的子模块/代码>.但是,到目前为止,我只能创建两个顶级模块,foo_foo.

I would like to be able to package it in such a way that the Python wrapper is the top level module foo and the Python C extension is a submodule located at foo._foo. However I have so far only been able to create two top level modules, foo and _foo.

我需要在 setup.pyinit_foo C 函数中做什么来完成这个?

What do I need to do in setup.py and in the init_foo C function in order to accomplish this?

(我的问题与 这个)

当前目录结构:

foo/
    foo/
        __init__.py
    foo.c
    setup.py
    tests.py

setup.py 看起来像:

from distutils.core import setup, Extension

module = Extension('_foo',
                   sources=['foo.c'])

setup(name='foo', packages=['foo'], ext_modules=[module])

foo.c 看起来像:

PyMODINIT_FUNC init_foo(void) {
    PyObject *m;
    m = Py_InitModule("_foo", FooMethods);
    // ..
}
int main(int argc, char *argv[]) {
    Py_SetProgramName(argv[0])
    Py_Initialize();
    init_pychbase();
}

foo/__init__.py 看起来像:

from _foo import _Foo, _Bar, _Baz

class Foo(object):
    def __init__(self):
        self._foo = _Foo()

推荐答案

如链接问题中所述,解决方案很简单,只需将 _foo 更改为 foo._foo:

As mentioned in the linked question, the solution is simply to change _foo to foo._foo:

from distutils.core import setup, Extension

module = Extension('foo._foo',
                   sources=['foo.c'])

setup(name='foo', packages=['foo'], ext_modules=[module])

我的问题是我从 foo 模块所在的同一目录中运行我的 tests.py.

My issue was that I was running my tests.py from the same directory as the foo module was located in.

我通过将其放入自己的目录来解决此问题:

I fixed this by bringing it into its own directory:

/foo
    /foo
        __init__.py
    foo.c
    setup.py
    /tests
         test.py

这篇关于如何打包 Python C 扩展,使其成为普通 Python 模块的子模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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