SourceXtractorPlusPlus  0.11
Please provide a description of the project.
Python.cpp
Go to the documentation of this file.
1 
17 #include <Python.h>
18 #include <ElementsKernel/Logging.h>
19 #include <boost/python/extract.hpp>
20 #include <boost/python/handle.hpp>
21 #include <boost/python/object.hpp>
22 
23 #include "SEUtils/Python.h"
24 
25 
26 namespace py = boost::python;
27 
28 namespace SourceXtractor {
29 
31  GILStateEnsure ensure;
32 
33  PyObject * ptype, *pvalue, *ptraceback;
34  PyErr_Fetch(&ptype, &pvalue, &ptraceback);
35  PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
36 
37  py::handle<> handle_type(ptype);
38  py::handle<> handle_value(pvalue);
39  py::handle<> handle_traceback(py::allow_null(ptraceback));
40 
41  // Get only the error message
42  py::object err_msg_obj(py::handle<>(PyObject_Str(pvalue)));
43  std::string err_msg = py::extract<std::string>(err_msg_obj);
44  if (err_msg.empty()) {
45  py::object err_repr_obj(py::handle<>(PyObject_Repr(pvalue)));
46  err_msg = py::extract<std::string>(err_repr_obj);
47  }
48 
49  // Dump to ERR the traceback
50  logger.error() << "Python exception " << err_msg;
51 
52  if (ptraceback) {
53  py::object traceback(handle_traceback);
54  while (traceback) {
55  long lineno = py::extract<long>(traceback.attr("tb_lineno"));
56  std::string filename = py::extract<std::string>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));
57  std::string funcname = py::extract<std::string>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
58 
59  logger.error() << "File \"" << filename << "\", line " << lineno << ", in " << funcname;
60 
61  traceback = traceback.attr("tb_next");
62  }
63  }
64 
65  // Done
66  PyErr_Clear();
67  return Elements::Exception(err_msg);
68 }
69 
71  m_state = PyGILState_Ensure();
72 }
73 
75  PyGILState_Release(m_state);
76 }
77 
78 } // end SourceXtractor
T empty(T... args)
static Elements::Logging logger
Elements::Exception pyToElementsException(Elements::Logging &logger)
Definition: Python.cpp:30
STL class.
PyGILState_STATE m_state
Definition: Python.h:51
string filename
Definition: conf.py:63
void error(const std::string &logMessage)