【问题标题】:(Python C API) PyRun_StringFlags missing builtin functions?(Python C API)PyRun_StringFlags 缺少内置函数?
【发布时间】:2012-05-27 20:42:24
【问题描述】:

我正在尝试在我的宠物项目中嵌入一些 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__ 不见了。如何加载缺少的模块或我缺少的任何东西?

谢谢。

【问题讨论】:

    标签: python python-c-api python-embedding


    【解决方案1】:

    一种方式:

    g = PyDict_New();
    if (!g)
        return NULL;
    
    PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());
    

    然后将g 传递为globals

    【讨论】:

    • 谢谢! PyEval_GetBuiltins 正是我所需要的。我只是不知道如何找到它。
    • 我用这个。但是在代码if not 'nickname' in vars(__builtins__): 中出现vars() argument must have __dict__ attribute 错误
    【解决方案2】:

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

    PyObject *globals = PyModule_GetDict(PyImport_AddModule("__main__"));
    PyObject *obj = PyRun_String("...", Py_file_input, globals, globals);
    Py_DECREF(obj);
    

    这实际上是PyRun_SimpleStringFlags 在内部所做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2017-07-24
      • 1970-01-01
      • 2017-06-11
      • 2011-04-30
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多