Search code examples
pythonpython-c-api

Evaluating Python Code From the CAPI and getting Output


I'm trying to emulate code.InteractiveInterpreter from the embedded Python C API. I'm using PyEval_Evalcode to evaluate the user input. I am trying to evaluate user input in the interpreter and return the output as a string (just like the interpreter would). However, PyEval_Evalcode returns a multitude of datatypes wrapped in PyObject*. Is there any way to do what I am trying to do?

Constraints: It needs to be done using the embedding api. Cannot be done using PyRun_RunSimpleString() and laying down a code.InteractiveInterpreter.


Solution

  • The object returned by PyEval_Evalcode() can be transformed to a Python string using PyObject_Repr() or PyObject_Str(). The resultant python string can be turned into a regular C string with PyString_AsString().