Files
rtabmap/corelib/src/python/PythonInterface.cpp
T

76 lines
1.9 KiB
C++
Raw Normal View History

2021-01-17 01:56:27 -05:00
/*
* PythonSingleTon.h
*
* Created on: Jan. 14, 2021
* Author: mathieu
*/
#include <rtabmap/core/PythonInterface.h>
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UThread.h>
#include <pybind11/embed.h>
#include <filesystem>
2021-01-17 01:56:27 -05:00
namespace rtabmap {
PythonInterface::PythonInterface()
2021-01-17 01:56:27 -05:00
{
UINFO("Initialize python interpreter");
guard_ = new pybind11::scoped_interpreter();
// Tell Python to look in this directory for DLLs
2026-04-14 12:09:41 -07:00
#ifdef _WIN32
std::string exe_dir = std::filesystem::current_path().string();
pybind11::module_ os = pybind11::module_::import("os");
os.attr("add_dll_directory")(exe_dir);
2026-04-14 12:09:41 -07:00
#endif
pybind11::module::import("threading");
release_ = new pybind11::gil_scoped_release();
2021-01-17 01:56:27 -05:00
}
PythonInterface::~PythonInterface()
{
UINFO("Finalize python interpreter");
delete release_;
delete guard_;
2021-01-17 01:56:27 -05:00
}
std::string getPythonTraceback()
2021-01-17 01:56:27 -05:00
{
// Author: https://stackoverflow.com/questions/41268061/c-c-python-exception-traceback-not-being-generated
PyObject* type;
PyObject* value;
PyObject* traceback;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
std::string fcn = "";
fcn += "def get_pretty_traceback(exc_type, exc_value, exc_tb):\n";
fcn += " import sys, traceback\n";
fcn += " lines = []\n";
fcn += " lines = traceback.format_exception(exc_type, exc_value, exc_tb)\n";
fcn += " output = '\\n'.join(lines)\n";
fcn += " return output\n";
PyRun_SimpleString(fcn.c_str());
PyObject* mod = PyImport_ImportModule("__main__");
UASSERT(mod);
PyObject* method = PyObject_GetAttrString(mod, "get_pretty_traceback");
UASSERT(method);
PyObject* outStr = PyObject_CallObject(method, Py_BuildValue("OOO", type, value, traceback));
std::string pretty;
if(outStr)
pretty = PyBytes_AsString(PyUnicode_AsASCIIString(outStr));
Py_DECREF(method);
Py_DECREF(outStr);
Py_DECREF(mod);
return pretty;
}
}