[C++-sig] Re: how to get python expection infomation in c++?

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Thu Apr 8 13:41:31 CEST 2004


My point was about getting the error message not printed in stderr
(because I have a GUI and reporting the error must be done in it). As
PyErr_Print() writes its message to sys.stderr, the only way I found to
get the message is to redirect sys.stderr to a pipe and to read this
pipe. I event looked into Python code to see if there were a function to
write the error where I want it to, but I didn't find any !

Pierre

On Thu, 2004-04-08 at 13:28, David Abrahams wrote:
> Pierre Barbier de Reuille <pierre.barbier at cirad.fr> writes:
> 
> > Hi !
> >
> > I had the same problem ... so I redirected sys.stderr to a pipe I opened
> > before ...
> >
> > Here's the few lines that do that :
> >
> >       int nb_err[2];
> >       FILE* err, *rd_err;
> >       pipe( nb_err );
> >       // Initialise the pipe
> >       err = fdopen( nb_err[ 1 ], "w" );
> >       setlinebuf( err );
> >       rd_err = fdopen( nb_err[ 0 ], "r" );
> >       // Install stderr
> >       boost::python::handle<> herr( PyFile_FromFile(err, "embedded_err",
> > "w", fclose ) );
> >       object obj_err( herr );
> >       main_namespace[ "__embedded_stderr__" ] = obj_err;
> >       PyRun_String( "sys.stderr = __embedded_stderr__", Py_file_input,
> > main_namespace.ptr(), main_namespace.ptr() );
> >
> > After that, you can read the errors in rd_err. The assumption is made
> > that the sys module is already imported ! Also, main_namespace is a
> > boost::python::dict wrapping the __main__ module dictionnary. As I don't
> > need to interpret what's written but just to forward it to the user,
> > this interface is ok for me (I just have a thread dedicated to listen
> > the error output).
> 
> Easier approaches are detailed here:
> 
>     http://tinyurl.com/uiis
> 
> and in:
> 
>     http://tinyurl.com/uiiu
> 
> FWIW,
-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68 





More information about the Cplusplus-sig mailing list