Skip to content

Commit

Permalink
attempt to get a full traceback when numpy fails to import
Browse files Browse the repository at this point in the history
  • Loading branch information
hobu committed Oct 2, 2012
1 parent 8c15723 commit 095d180
Showing 1 changed file with 66 additions and 4 deletions.
70 changes: 66 additions & 4 deletions src/plang/Invocation.cpp
Expand Up @@ -61,11 +61,73 @@ void Invocation::numpy_init()
// this macro is defined be NumPy and must be included
if (_import_array() < 0)
{
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
char *message = PyString_AsString(pvalue);
PyObject* tracebackModule;
PyObject* tracebackDictionary;
PyObject* tracebackFunction;
tracebackModule = PyImport_ImportModule("traceback");
if (!tracebackModule)
{
throw python_error("unable to load traceback module while importing numpy inside PDAL");
}

tracebackDictionary = PyModule_GetDict(tracebackModule);

tracebackFunction = PyDict_GetItemString(tracebackDictionary, "format_exception");
if (!tracebackFunction)
{
throw python_error("unable to find traceback function while importing numpy inside PDAL");
}

if (!PyCallable_Check(tracebackFunction))
{
throw python_error("invalid traceback function while importing numpy inside PDAL");
}


// get exception info
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);

std::string mssg = "";
if (traceback)
{
// create an argument for "format exception"
PyObject* args = PyTuple_New(3);
PyTuple_SetItem(args, 0, type);
PyTuple_SetItem(args, 1, value);
PyTuple_SetItem(args, 2, traceback);

// get a list of string describing what went wrong
PyObject* output = PyObject_CallObject(tracebackFunction, args);

// print error message
int i, n = PyList_Size(output);
for (i=0; i<n; i++) mssg += PyString_AsString(PyList_GetItem(output, i));

// clean up
Py_XDECREF(args);
Py_XDECREF(output);
}
else if (value != NULL)
{
PyObject *s = PyObject_Str(value);
const char* text = PyString_AS_STRING(s);
Py_DECREF(s);
mssg += text;
}
else
{
mssg = "unknown error";
}

Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(traceback);


std::ostringstream oss;
oss << "unable to initialize NumPy with error '" << std::string(message) << "'";
oss << "unable to initialize NumPy with error '" << std::string(mssg) << "'";
throw python_error(oss.str());
}
}
Expand Down

0 comments on commit 095d180

Please sign in to comment.