I’m writing a Python terminal GUI in C++. I’m using the following code to run a user-typed Python command-line:
void RunTerminalCommand (char * line)
{
PyObject *py_main, *py_dict;
py_main = PyImport_AddModule("__main__");
py_dict = PyModule_GetDict(py_main);
PyObject * PyRes = PyRun_String(line, Py_single_input, py_dict, py_dict);
return 0;
}
It works very well, with the command line being executed and the result being printed on the output window via stdout. But whenever the Python command line leads to a Python error, it stops working: My stdout doesn’t receive any data
Notes:
-
PyRes always returns NULL, even before the error line is injected
-
I don’t know if I should call PyImport_AddModule every time. But it seems to work this way.
-
If I use PyRun_SimpleString(line) insted of PyRun_String(line, Py_single_input, py_dict, py_dict), it always work, and I still get the Error messages via stdout/stderr. But this call doesn’t send the result of command line evaluatiosn to stdout, so I don’t want to use it. For example, the command line “2+2” will print “4” on stdout when I use PyRun_String, but not when I use PyRun_SimpleString.
I’ve gone through a similar problem, and solved it by adding a “\n” (Carriage-return) using Py_Run_SimpleString right after the user command line, as in the example:
It doesn’t work if you add the “\n” at the end of PyRun_String. It needs to be a separated call to PyRun_SimpleString