Skip to content

Instantly share code, notes, and snippets.

@ndevenish
Last active January 19, 2018 11:50
Show Gist options
  • Save ndevenish/5a3d099638ec1c83549ab3ef4b6d0a0d to your computer and use it in GitHub Desktop.
Save ndevenish/5a3d099638ec1c83549ab3ef4b6d0a0d to your computer and use it in GitHub Desktop.
Print a python stacktrace from a c method
#include <iostream>
#include <Python.h>
inline void print_stacktrace()
{
std::cout << "==== Python Stacktrace ======================================" << std::endl;
PyObject *module_name, *pyth_module, *pyth_func;
// Import the python traceback module
module_name = PyString_FromString("traceback");
pyth_module = PyImport_Import(module_name);
Py_DECREF(module_name);
// Get and call the function
pyth_func = PyObject_GetAttrString(pyth_module, "print_stack");
if (pyth_func && PyCallable_Check(pyth_func)) {
PyObject *pyth_val;
pyth_val = PyObject_CallFunctionObjArgs(pyth_func, NULL);//ptype, pvalue, ptraceback,
Py_DECREF(pyth_val);
}
std::cout << "=============================================================" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment