PythonInterface.cpp
Go to the documentation of this file.
1 /*
2  * PythonSingleTon.h
3  *
4  * Created on: Jan. 14, 2021
5  * Author: mathieu
6  */
7 
11 #include <pybind11/embed.h>
12 
13 namespace rtabmap {
14 
16 {
17  UINFO("Initialize python interpreter");
18  guard_ = new pybind11::scoped_interpreter();
19  pybind11::module::import("threading");
20  release_ = new pybind11::gil_scoped_release();
21 }
22 
24 {
25  UINFO("Finalize python interpreter");
26  delete release_;
27  delete guard_;
28 }
29 
30 std::string getPythonTraceback()
31 {
32  // Author: https://stackoverflow.com/questions/41268061/c-c-python-exception-traceback-not-being-generated
33 
34  PyObject* type;
35  PyObject* value;
36  PyObject* traceback;
37 
38  PyErr_Fetch(&type, &value, &traceback);
39  PyErr_NormalizeException(&type, &value, &traceback);
40 
41  std::string fcn = "";
42  fcn += "def get_pretty_traceback(exc_type, exc_value, exc_tb):\n";
43  fcn += " import sys, traceback\n";
44  fcn += " lines = []\n";
45  fcn += " lines = traceback.format_exception(exc_type, exc_value, exc_tb)\n";
46  fcn += " output = '\\n'.join(lines)\n";
47  fcn += " return output\n";
48 
49  PyRun_SimpleString(fcn.c_str());
50  PyObject* mod = PyImport_ImportModule("__main__");
51  UASSERT(mod);
52  PyObject* method = PyObject_GetAttrString(mod, "get_pretty_traceback");
53  UASSERT(method);
54  PyObject* outStr = PyObject_CallObject(method, Py_BuildValue("OOO", type, value, traceback));
55  std::string pretty;
56  if(outStr)
57  pretty = PyBytes_AsString(PyUnicode_AsASCIIString(outStr));
58 
59  Py_DECREF(method);
60  Py_DECREF(outStr);
61  Py_DECREF(mod);
62 
63  return pretty;
64 }
65 
66 }
UINFO
#define UINFO(...)
PyBytes_AsString
#define PyBytes_AsString
type
rtabmap::getPythonTraceback
std::string getPythonTraceback()
Definition: PythonInterface.cpp:30
rtabmap::PythonInterface::release_
pybind11::gil_scoped_release * release_
Definition: PythonInterface.h:34
UASSERT
#define UASSERT(condition)
PythonInterface.h
rtabmap::PythonInterface::PythonInterface
PythonInterface()
Definition: PythonInterface.cpp:15
ULogger.h
ULogger class and convenient macros.
embed.h
rtabmap::PythonInterface::guard_
pybind11::scoped_interpreter * guard_
Definition: PythonInterface.h:33
UThread.h
glm::mod
GLM_FUNC_DECL genType mod(genType const &x, genType const &y)
rtabmap
Definition: CameraARCore.cpp:35
value
value
rtabmap::PythonInterface::~PythonInterface
virtual ~PythonInterface()
Definition: PythonInterface.cpp:23


rtabmap
Author(s): Mathieu Labbe
autogenerated on Thu Jul 25 2024 02:50:15