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

Gavin Doughtie gdoughtie at anim.dreamworks.com
Thu May 29 18:13:36 CEST 2003


Here's what I did:

std::string PythonInterpreterImpl::pythonError() const
{
   PyObject* errType(NULL);
   PyObject* errValue(NULL);
   PyObject* errTraceback(NULL);

   PyErr_Fetch(&errType, &errValue, &errTraceback);
   if (NULL == errValue)
     {
       return "Unknown Python Error";
     }

   handle<> errHandle(errValue);
   str errObj(errHandle);
   char *errMsg = extract< char* >(errObj);
   return errMsg;
}

Achim Domma (ProCoders) wrote:
> 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. 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?
> Has somebody an working example on how to get the traceback or could point
> me to the right direction?
> 
> regards,
> Achim
> 
> 
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
> 

-- 
Gavin Doughtie
DreamWorks SKG
(818) 695-3821





More information about the Cplusplus-sig mailing list