How can I get the error message if py::exec an incorrect statement? #3596
Unanswered
softempire
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there,
Does anyone meet the issue before?
I want to get the output/error when exec some Python statement from a C++ program. And then display the message on the GUI. But I can't get the message if the python statement is incorrect like "jajslkjgkajljslkjglakj"
`int main(int argc, char *argv[])
{
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
class CatchOutErr:\n
def init(self):\n
self.value = 'placeholder'\n
def write(self, txt):\n
self.value += txt\n
catchOutErr = CatchOutErr()\n
oldstdout = sys.stdout\n
sys.stdout = catchOutErr\n
oldstderr = sys.stderr\n
sys.stderr = catchOutErr\n
"; //this is python code to redirect stdouts/stderr
//I can get the result message "placeholder123"
py::exec("print(123)");
//I can 't get the error message if run the following statement
//py::exec("error print(123)");
}
catch (...)
{
auto catcher = PyObject_GetAttrString(pModule, "catchOutErr"); //get our catchOutErr created above
auto output = PyObject_GetAttrString(catcher, "value"); //get the stdout and stderr from our catchOutErr object
auto strOutput = ObjectToString(output);
}
}`
Beta Was this translation helpful? Give feedback.
All reactions