I'm doing a functools.partial(print, flush=True) in the C-API before calling PyRun_File (please see Python C-API and PyRun_File: Using "import functools and partial(print, flush=True)").
The print works in the __main__ module, but isn't available in imported modules.
I'll try to create a simple example to describe the issue:
C-code
Please see full code example in https://stackoverflow.com/questions/67875182/ ... ... PyObject* newPrint = PyObject(partial, args, kwargs); PyObject* main_module = PyImport_ImportModule("__main__"); PyObject* pdict = PyModule_GetDict(main_module); PyDict_SetItemString(pdict, "print", newPrint); FILE* fp = fopen("prg_1.py", "r"); PyObject* pval = PyRun_File(fp, "prg_1.py", Py_file_input, pdict, pdict); And the Python files:
prg_1_func.py
import time def execute(): for i in range(5): print(i, end=" ") time.sleep(1) prg_1.py
import prg_1_func if __name__ == "__main__": print("Start...") prg_1_func.execute() print("...End") The new print function is available in __main__ due to the call to PyDict_SetItemString(pdict, "print", newPrint).
But how can I get it to be "visible" in prg_1_func.py as well?
I can not/do not want to edit any of the Python files!
I came up with one idea but have no clue if it is even achievable, i.e. import everything and postpone the actual execution of the code?
PyObject* newPrint = PyObject(partial, args, kwargs); PyObject* main_module = PyImport_ImportModule("__main__"); PyObject* pdict = PyModule_GetDict(main_module); Read all modules that will be imported, without executing the code! for all modules as MOD do: PyDict_SetItemString(pdict, MODname + ".print", newPrint); FILE* fp = fopen("prg_1.py", "r"); PyObject* pval = PyRun_File(fp, "prg_1.py", Py_file_input, pdict, pdict); If anyone else has encountered the same or a similar problem and has managed to solve it, how did you do it? :o)
printfor the entire program, you have to do so inbuiltins. That's not at all related to the C-API, though. Are you able to do this in pure Python without jumping through the hoops of the C-API? The error in your previous question would already have been the same in pure Python and the C-API, the C-API was just obfuscating things.PyRun_File, which is why I tried to do thefunctools.partial(print, flush=True)before callingPyRun_File. With the help from DavidW it did work, until I encountered the problem I've stated in this question. The info and the link you provided might point me in the right direction, so I will have a look.