Python C Extension: PyEval_GetLocals() returns NULL
<p>I need to read local variables from Python in C/C++. When I try to <code>PyEval_GetLocals</code>, I get a NULL. This happens although Python is initialized. The following is a minimal example.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;Python.h&gt;

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

<p>In <a href="https://docs.python.org/3/c-api/reflection.html#c.PyEval_GetLocals" rel="nofollow">the manual</a>, it says that it returns NULL if no frame is running, but... there's a frame running!</p>

<p><strong>What am I doing wrong?</strong></p>

<p>I'm running this in Debian Jessie.</p>

<p>Turns out the right way to access variables in the scope is:</p>

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

python c++ c python-c-extension python-extensions