在 python 中使用 C 扩展,而不将其作为模块安装

using a C extension in python, without installing it as a module

我正在为 python 编写 C 扩展。我暂时只是在试验,我写了一个如下所示的 hello world 扩展:

#include <Python2.7/Python.h>

static PyObject* helloworld(PyObject* self)
{
    return Py_BuildValue("s", "Hello, Python extensions!!");
}

static char helloworld_docs[] = "helloworld( ): Any message you want to put here!!\n";

static PyMethodDef helloworld_funcs[] = {
    {"helloworld", (PyCFunction)helloworld, METH_NOARGS, helloworld_docs},
    {NULL,NULL,0,NULL}
};

void inithelloworld(void)
{
    Py_InitModule3("helloworld", helloworld_funcs,"Extension module example!");
}

从我编写的 setup.py 文件安装代码并从命令行安装它后,代码运行良好

python setup.py install

我想要的是:

我想将 C 文件用作 python 扩展模块,而不安装它,也就是说,我想将它用作我项目中的另一个 python 文件,而不是文件我需要在我的 python 模块开始使用它的功能之前安装它。有什么办法可以做到这一点吗?

您可以通过不扩展 python 而是将其嵌入您的应用程序来创建您的 "own interpreter"。这样,您的对象将始终可供 运行 您的程序的用户使用。在某些情况下这是很常见的事情,例如查看 Blender 项目,其中已经包含所有 bpybmeshbge 模块。

缺点是,您的用户不能直接使用 python 命令,他们必须改用您的 hello_world_python。 (但当然你也可以将你的扩展作为一个模块提供。)这也意味着,你必须为你想要支持的所有平台编译和分发你的应用程序——如果你想将它作为二进制文件分发,让您的用户生活更轻松。

有关将 python 嵌入程序的更多信息,请阅读文档的相应部分:

Embedding Python in Another Application

Personal suggestion: Use Python 3.5 whenever you can, and stop supporting the old 2.x versions. For more information, read this article: Should I use Python 2 or Python 3 for my development activity?

您可以简单地编译扩展而不安装(通常类似于 python setup.py build)。然后你必须确保解释器可以找到编译的模块(例如通过将它复制到导入它的脚本旁边,或者设置 PYTHONPATH)。