如何将我的 Python C 模块放入包中? [英] How to put my Python C-module inside package?

查看:71
本文介绍了如何将我的 Python C 模块放入包中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个包下收集多个 Python 模块,因此它们不会从全局 Python 包和模块集中保留太多名称.但是我对用 C 编写的模块有问题.

I would like to gather multiple Python modules under one package, so they do not reserve too many names from global set of python packages and modules. But I have problems with modules that are written in C.

这是一个非常简单的示例,直接来自官方 Python 文档.您可以在页面底部从这里找到它:http://docs.python.org/distutils/examples.html

Here is a very simple example, straight from the official Python documentation. You can find it at the bottom of the page from here: http://docs.python.org/distutils/examples.html

from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      ext_modules=[Extension('foopkg.foo', ['foo.c'])],
      )

我的 foo.c 文件是这样的

My foo.c file looks like this

#include <Python.h>

static PyObject *
foo_bar(PyObject *self, PyObject *args);

static PyMethodDef FooMethods[] = {
    {
        "bar",
        foo_bar,
        METH_VARARGS,
        ""
    },
    {NULL, NULL, 0, NULL}
};

static PyObject *
foo_bar(PyObject *self, PyObject *args)
{
    return Py_BuildValue("s", "foobar");
}

PyMODINIT_FUNC
initfoo(void)
{
    (void)Py_InitModule("foo", FooMethods);
}

int
main(int argc, char *argv[])
{
    // Pass argv[0] to the Python interpreter
    Py_SetProgramName(argv[0]);

    // Initialize the Python interpreter.  Required.
    Py_Initialize();

    // Add a static module
    initfoo();

    return 0;
}

它可以正常构建和安装,但我无法导入 foopkg.foo!如果我将它重命名为foo",它就可以完美运行.

It builds and installs fine, but I cannot import foopkg.foo! If I rename it to just "foo" it works perfectly.

有什么想法可以让foopkg.foo"工作吗?例如,将 C 代码中的foo"从 Py_InitModule() 更改为foopkg.foo"没有帮助.

Any ideas how I can make the "foopkg.foo" work? For example changing "foo" from Py_InitModule() in C code to "foopkg.foo" does not help.

推荐答案

foopkg文件夹下必须有__init__.py文件,否则Python无法识别为一个包裹.

There must be an __init__.py file in the foopkg folder, otherwise Python does not recognize as a package.

setup.py所在的位置创建一个foopkg文件夹,并在其中放置一个空文件__init__.py,并添加一个行到setup.py:

Create a foopkg folder where setup.py is, and put an empty file __init__.py there, and add a packages line to setup.py:

from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      packages=['foopkg'],
      ext_modules=[Extension('foopkg.foo', ['foo.c'])],
      )

这篇关于如何将我的 Python C 模块放入包中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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