Python Forum
C API: Writing Executed Code to a File - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: C API: Writing Executed Code to a File (/thread-22560.html)



C API: Writing Executed Code to a File - myanrueller - Nov-17-2019

I am working on a game that teaches programming through Python. To do this, I am embedding the Python interpreter in a C/C++ game. I am struggling capturing the conversion of the executed code properly however. While my initial thoughts to use C/C++ file streams, that did not work. The problem I'm running into is that I'm not quite sure how to call the API to get the correct data to write to the file. Below is my code.

PyObject  *ioMod, *openedFile;
PyGILState_STATE gilState = PyGILState_Ensure();
//storeOut.open("store.txt");

PyObject* objectsRepresentation = PyObject_Str(Object);
PyObject* encoded = PyUnicode_AsEncodedString(objectsRepresentation, "utf-8", "strict");

ioMod = PyImport_ImportModule("io");
openedFile = PyObject_CallMethod(ioMod, "open", "ss", "store.txt", "wb");
Py_DECREF(ioMod);

PyObject_CallMethod(openedFile, "write", "y", PyObject_Str(encoded));
PyObject_CallMethod(openedFile, "flush", NULL);
PyObject_CallMethod(openedFile, "close", NULL);
Py_DECREF(openedFile);
As it stands, when I type any basic arithmetic function like 2 + 2, it writes the correct result to the "store.txt" file. When a function like 'print' is called however, what gets written to the file is 'None'. I'm unsure where the result is going. I'm also running some error checking in C++ to see what is going on. Running the code object prints the correct value to the debug console everytime. The code is capturing and returning the proper value to the console. But in the file and game it prints 'None' when a Print function is called.

Am I calling the wrong function, or not capturing the data properly?

Thanks for the help!