Python C Extension: PyEval_GetLocals() returns NULL

落爺英雄遲暮 提交于 2019-12-24 07:38:10

问题


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();

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

What am I doing wrong?

I'm running this in Debian Jessie.


回答1:


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();


来源:https://stackoverflow.com/questions/40046330/python-c-extension-pyeval-getlocals-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!