[C++-sig] Displaying PyErr_Print() error

Daryle Walker darylew at hotmail.com
Sat Nov 29 03:06:28 CET 2003


On 11/27/03 7:07 AM, "Paul Grenyer" <paul at paulgrenyer.co.uk> wrote:

> I've intergrated boost.python into a COM object and therefore there is
> no std::cerr console to display the error message generated by
> PyErr_Print() after an exception is thrown.

I'm only on this list because I'm involved with Boost and it suggested that
this list is used for Boost.Python discussion.

> I've tried redirecting std::cerr to a stream:
> 
> catch( const error_already_set& )
> {
>   std::stringstream str;
>   std::streambuf* streamBuffer = std::cerr.rdbuf( str.rdbuf() );
> 
>   PyErr_Print();
>   std::cerr << python << std::endl;
> 
>   std::cerr.rdbuf( streamBuffer );
>   throw BadPython( str.str(), __FILE__, __LINE__ );
> }        

If you got Boost (for Boost.Python), there's a different file, called
"ios_state.hpp" with a class template called "basic_ios_rdbuf_saver" that
can encapsulate your stream-buffer switching under RAII.

(In your code above, you could use an std::stringbuf object directly instead
of a std::stringstream.)

> The contents of "python", a string holding the python code that
> generated the exception, is correctly send to "str", but the exception
> message isn't.
> 
> Am I doing something wrong? Is there another way to get the error
> generated by PyErr_Print() in a string?

A general programming suggestion: do you even know if "PyErr_Print" actually
uses immediate calls to "std::cerr" in its implementation?  Your plan won't
work if the answer is "no".

-- 
Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT hotmail DOT com





More information about the Cplusplus-sig mailing list