我正在尝试在我喜欢的项目中嵌入一些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;
}(我知道我没有清理任何引用。这是一个示例。)
它可以通过以下方式编译
c++ $(python-config --includes) $(python-config --libs) test.cpp -o test如果我运行它,我会得到以下错误:
$ ./test
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name 'dict' is not defined似乎内置函数没有加载。我也不能import任何东西。我知道__import__不见了。我如何加载缺少的模块或我缺少的任何东西?
谢谢。
发布于 2012-05-21 19:10:45
一种方法:
g = PyDict_New();
if (!g)
return NULL;
PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());然后以globals的身份传递g。
发布于 2012-08-21 06:56:49
您还可以在__main__模块命名空间中执行代码:
PyObject *globals = PyModule_GetDict(PyImport_AddModule("__main__"));
PyObject *obj = PyRun_String("...", Py_file_input, globals, globals);
Py_DECREF(obj);这实际上是PyRun_SimpleStringFlags在内部所做的事情。
https://stackoverflow.com/questions/10683713
复制相似问题