2

I am trying to run, in a C++ program, some python file that is actually included in the C++ code as a std::string called command.

I have been successful using PyRun_SimpleString(command.c_str()), but this prevents getting exception information.

I now try the following instead:

PyObject* result = PyRun_String(command.c_str(), Py_file_input, PyEval_GetGlobals(), PyEval_GetLocals());

However, this throws:

SystemError: frame does not exist

What am I doing wrong?

UPDATE:

I tried to split the process into compile+eval using the following:

PyObject* code = Py_CompileString(command.c_str(), filename.c_str(), Py_file_input);
PyObject* result = PyEval_EvalCode(code, PyEval_GetGlobals(), PyEval_GetLocals());

Now, the error is different:

SystemError: PyEval_EvalCodeEx: NULL globals

This is maybe more explanatory, as it says in the C API doc::

Return a dictionary of the global variables in the current execution frame, or NULL if no frame is currently executing.

I am not sure I understand what a frame is.

2
  • Can you please post the command string? Commented Dec 19, 2017 at 11:37
  • @p-a-o-l-o all commands fail. I tried, for instance, "import math" or "print(1)" Commented Dec 19, 2017 at 13:17

1 Answer 1

4

I found a solution. I probably have not understood when a frame is exectuting or not, but it turns out that just after launching the interpreter, no frames are running. That's why PyEval_GetGlobals() and PyEval_GetLocals() were returning NULL and caused errors later.

Instead, the namespace of the default module __main__ should be used as both globals and locals namespaces:

PyObject* d = PyModule_GetDict(PyImport_AddModule("__main__"));
PyObject* result = PyRun_String(command.c_str(), Py_file_input, d, d);
Py_DECREF(result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.