【问题标题】:Embedding Python in C for configuration files在 C 中嵌入 Python 以获取配置文件
【发布时间】:2010-10-20 08:45:51
【问题描述】:

我正在尝试将 python 嵌入到 c 中以使用它进行配置:

如果我这样做:

/******************************************************************************
* 
* Embeding Python Example
*
* To run: 
*   gcc -c test.c -o test.o -I"C:/Python25/include"
*   gcc -o test.exe test.o -L"C:/Python25/libs" -lpython25
*   test.exe
*
******************************************************************************/

#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *run;
    PyObject *globals = PyDict_New();
    PyObject *locals = PyDict_New();

    Py_Initialize();

    run = PyRun_String("from time import time,ctime\n"
                       "print 'Today is',ctime(time())\n"
                        "test = 5\n"
                        "print test\n", Py_file_input, globals, locals);


    Py_Finalize();
    return 0;
}

我从 Microsoft VIsual C++ 运行时收到运行时错误,并显示以下消息:

Exception exceptions.ImportError: '__import__ not found' in 'garbage collection' ignored
Fatal Python error: unexpected exception during garbage collection

我做错了什么?

【问题讨论】:

  • 仅供参考,Lua 比 Python 更适合轻量级嵌入和配置文件。

标签: python c configuration embedding


【解决方案1】:

你做错的正是我做错的。

您正在将自己的 globals 字典初始化为空。这意味着即使像 __import__ 这样的东西也没有为当前范围定义。

在您的简单示例中,您可以替换

run = PyRun_String("from time import time,ctime\n"
                   "print 'Today is',ctime(time())\n"
                    "test = 5\n"
                    "print test\n", Py_file_input, globals, locals);

PyRun_SimpleString("from time import time,ctime\n"
                   "print 'Today is',ctime(time())\n"
                   "test = 5\n"
                   "print test\n");

您可能也想完全删除 globalslocals

如果我知道如何访问 default 全局字典,我会在这里添加评论或编辑。

编辑:PyRun_SimpleStringFlags(Python 2.7.3)的实现如下所示:

int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
{
    PyObject *m, *d, *v;
    m = PyImport_AddModule("__main__");
    if (m == NULL)
        return -1;
    d = PyModule_GetDict(m);
    v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
    ...

因此,要获取 default 全局字典,您必须导入 __main__ 并获取 its 字典。这将包含所有默认的内置函数等。

【讨论】:

    【解决方案2】:

    在初始化 Python 引擎之前,您正在创建 2 个 Python 对象。

    另外,这很愚蠢。有很多 C 的 JSON 解析器。

    【讨论】:

    • +1。为什么要将完整的脚本语言解释器嵌入到您的应用中只是用作配置语言?
    • 我在初始化Python引擎后尝试初始化对象,但错误仍然存​​在。
    猜你喜欢
    • 2016-11-08
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多