(Python C API)PyRun_StringFlags缺少内置函数吗? [英] (Python C API) PyRun_StringFlags missing builtin functions?

查看:177
本文介绍了(Python C API)PyRun_StringFlags缺少内置函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的宠物项目中嵌入一些python.我已将问题简化为以下代码:

I am trying to embed some python in my pet project. I have reduced my problem to the following code:

#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;
}

(我知道我没有清理任何引用.这是一个示例.)

(I know I'm not cleaning up any references. This is an example.)

它可以通过

c++ $(python-config --includes) $(python-config --libs) test.cpp -o test

如果我运行它,会出现以下错误:

If I run it I get the following error:

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

似乎没有加载内置函数.我也不能import任何东西.我知道缺少__import__.如何加载缺少的模块或任何我缺少的模块?

It seems the the builtin functions aren't loaded. I also cannot import anything. I get that __import__ is missing. How can I load the missing modules or whatever I am missing?

谢谢.

推荐答案

一种方法:

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

PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());

然后将g作为globals传递.

这篇关于(Python C API)PyRun_StringFlags缺少内置函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆