Python C Extension: PyEval_GetLocals() returns NUL

2019-07-24 18:19发布

问题:

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