Python C Extension:PyEval_GetLocals()返回NULL [英] Python C Extension: PyEval_GetLocals() returns NULL

查看:274
本文介绍了Python C Extension:PyEval_GetLocals()返回NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C / C ++中从Python读取局部变量。当我尝试 PyEval_GetLocals ,我得到一个NULL。这发生,虽然Python初始化。以下是一个最小示例。

I need to read local variables from Python in C/C++. When I try to PyEval_GetLocals, I get a NULL. This happens although Python is initialized. The following is a minimal example.

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

Py_Initialize();
PyRun_SimpleString("a=5");
PyObject *locals = PyEval_GetLocals();
std::cout<<locals<<std::endl; //prints NULL (prints 0)
Py_Finalize();

手册,它说如果没有框架正在运行则返回NULL,但是有一个框架运行!

In the manual, it says that it returns NULL if no frame is running, but... there's a frame running!

我做错了什么?

我在Debian Jessie中执行此操作。

I'm running this in Debian Jessie.

推荐答案

找出范围内访问变量的正确方法是:

Turns out the right way to access variables in the scope is:

Py_Initialize();
PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");
std::cout<<globals<<std::endl; //Not NULL
Py_Finalize();

这篇关于Python C Extension:PyEval_GetLocals()返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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