pythonqt
pythonqt copied to clipboard
Emit error messages via signals or return them from function calls (optionally)
Hello!
Whenever a Python error occurs its description is sent to the stderr. I would like to emit a signal with error message instead. For instance, Qt’s own ECMAScript implementation, QJSEngine does not print to the stderr and instead returns a QJSValue containing error message, from which a string could be extracted and emitted via signal. It is very convenient.
The way I see it, this is how it could be done:
When error occurs during PythonQtObjectPtr::evalScript
or PythonQtObjectPtr::call
calls return QString (wrapped in QVariant) instead of invalid QVariant. PythonQt::hadError
would then tell whether this variant contains a “normal” string or an error message.
Or perhaps you could even give errors their own struct, with fields like type, message, etc, and the return value could be tested like this:
PythonQtObjectPtr main_module = PythonQt::self()->getMainModule();
QVariant result = main_module->evalScript (script);
if (result.canConvert<PythonQtErrorStruct>())
{
PythonQtErrorStruct error = result.value<PythonQtErrorStruct>();
emit errorOccured (error.type, error.message);
}
I am aware that PythonQt lets redirection of stderr, but this is not the same. Plus in some cases user might want to emit error via signal, and in other to simply print it to stderr, so just bluntly redirecting the entire error output seems like a cumbersome solution.
Modifying the return value is out of the question in my opinion, too many users might check for an invalid return value.
Emitting a signal or using a callback would perhaps work. The method PythonQt::handleError does the error handling, one could swap out the call to PyErr_Display with something that can be overridden by the user (after changing the handling of the printStack parameter).
But this is nothing I would work on, extracting the output printed by PyErr_Display seems to be more work than directly redirecting stderr.