[C++-sig] Re: embedding: getting exception information?

David Abrahams dave at boost-consulting.com
Thu May 29 17:39:46 CEST 2003

"Achim Domma \(ProCoders\)" <domma at procoders.net> writes:

> Hi,
> I'm embedding python in a COM object and want to get the information usually
> printed via PyErr_Print. I tried code like this:
> dict ns(... dict of __main__ like in the example ...);
> try {
>     handle<>(PyRun_String("import non_existing_module\n",
>     Py_file_input,ns.ptr(),ns.ptr()));
> } catch (error_already_set) {
>     // try to write error information to StringIO buffer
>     PyRun_String("import traceback,sys,StringIO\n"
>     "buf = StringIO.StringIO()\n"
>     "traceback.print_tb(sys.exc_info()[2],None,buf)\n"
>     "error = buf.getvalue()\n",
>     Py_file_input,ns.ptr(),ns.ptr());
>     PyErr_Clear();
>     std::string error = extract<std::string>(ns["error"]);
> }
> I tried also to use extract<const char*> but in both cases I get an
> exception in this line. 

What exception, and what message is associated with it?
Are you sure that buf is a Python string?

> I first tried to get the error information using the C API, but I
> could not find a solution. Af a little bit of googling I found this
> solution, but I don't know if it's ok: There is still an active
> exception, so could I safely continue to use the interpreter to
> output the error?  

That's what Python itself does, so I'm sure it's OK... though you
probably should do it inside a try block in case there's another
exception ;-)

> Has somebody an working example on how to get the traceback or could
> point me to the right direction?

Did you look at the embedding example in

Dave Abrahams
Boost Consulting

More information about the Cplusplus-sig mailing list