A few weeks ago I published a post that showed how to embedd Python into C++ and how to exchange data between the two languages. Today, I want to present a simple practice that comes in handy when embedding Python into C++: Rerouting Python’s standard output using CPython.
After initializing Python, the new destination of the output stream needs to be created using PyFile_FromString(…) and set to be the new standard output:
PyObject* pyStdOut = PyFile_FromString("CONOUT$", "w+"); PyObject* sys = PyImport_ImportModule("sys"); PyObject_SetAttrString(sys, "stdout", pyStdOut);
Basically that’s all it needs. When executing Python script via PyRun_String(…), all calls to print(…) will write the data directly to pyStdOut.
Ater the Python script is finished, the data in pyStdOut can be retrieved and further processed with C++ by converting it using PyFile_AsFile(…):
FILE* pythonOutput = PyFile_AsFile(pyStdOut);