(Python C API)PyRun_StringFlags缺少内置函数?

Sim*_*mon 10 python python-embedding python-c-api

我想在我的宠物项目中嵌入一些python.我已将问题减少到以下代码:

#include <Python.h>
#include "iostream"

int main(int argc, char *argv[])
{
    Py_Initialize();

    PyObject *globals = Py_BuildValue("{}");
    PyObject *locals = Py_BuildValue("{}");

    PyObject *string_result = PyRun_StringFlags(
        "a=5\n"
        "s='hello'\n"
        "d=dict()\n"
        ,
        Py_file_input, globals, locals, NULL);
    if ( PyErr_Occurred() ) {PyErr_Print();PyErr_Clear();return 1;}
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

(我知道我没有清理任何参考文献.这是一个例子.)

它可以编译

c++ $(python-config --includes) $(python-config --libs) test.cpp -o test
Run Code Online (Sandbox Code Playgroud)

如果我运行它,我会收到以下错误:

$ ./test 
Traceback (most recent call last):
  File "<string>", line 3, in <module>
NameError: name 'dict' is not defined
Run Code Online (Sandbox Code Playgroud)

看来内置函数没有加载.我也import什么都没有.我明白了__import__.如何加载丢失的模块或我遗漏的任何内容?

谢谢.

Eli*_*sky 11

单程:

g = PyDict_New();
if (!g)
    return NULL;

PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());
Run Code Online (Sandbox Code Playgroud)

再经过g作为globals.


Amr*_*mro 6

您还可以在__main__模块命名空间内执行代码:

PyObject *globals = PyModule_GetDict(PyImport_AddModule("__main__"));
PyObject *obj = PyRun_String("...", Py_file_input, globals, globals);
Py_DECREF(obj);
Run Code Online (Sandbox Code Playgroud)

这实际上是PyRun_SimpleStringFlags内部的.