[solved] C API version of str(exception) is not the same as pure python version
Barry Scott
barry at barrys-emacs.org
Sun Feb 10 10:42:56 EST 2019
On Sunday, 10 February 2019 11:59:16 GMT Barry Scott wrote:
> When I use the C API to get the str() of an execption I see this text:
>
> <class 'TypeError'>
>
> But python reports the following for the same exception:
>
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> What do I need to do in the C API to get the the same text for the
> exception?
>
> PyObject *err = PyErr_Occurred();
> if( err != 0 )
> {
> PyObject *u_why = PyObject_Str( err );
> PyObject *b_why = PyUnicode_AsEncodedString( u_why, "utf-8",
> "strict" );
> int size = PyBytes_Size( b_why );
> char *why = PyBytes_AsString( b_why );
> printf("Error: %*s\n", size, why );
> return 0;
> }
Using this code fixes the problem as Stefan pointed out I had the type of the
exception and not the value of the exception.
if( PyErr_Occurred() )
{
PyObject *type, *value, *trace;
PyErr_Fetch( &type, &value, &trace );
PyObject *u_why = PyObject_Str( value );
PyObject *b_why = PyUnicode_AsEncodedString( u_why, "utf-8", "strict"
);
int size = PyBytes_Size( b_why );
char *why = PyBytes_AsString( b_why );
printf("Error: %*s\n", size, why );
return 0;
}
More information about the Python-list
mailing list