Returns a PyObject containing a string, or null
| 49 | |
| 50 | // Returns a PyObject containing a string, or null |
| 51 | void TryAppendTraceback(PyObject* ptype, PyObject* pvalue, PyObject* ptraceback, |
| 52 | string* out) { |
| 53 | // The "traceback" module is assumed to be imported already by script_ops.py. |
| 54 | PyObject* tb_module = PyImport_AddModule("traceback"); |
| 55 | |
| 56 | if (!tb_module) { |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | PyObject* format_exception = |
| 61 | PyObject_GetAttrString(tb_module, "format_exception"); |
| 62 | |
| 63 | if (!format_exception) { |
| 64 | return; |
| 65 | } |
| 66 | |
| 67 | if (!PyCallable_Check(format_exception)) { |
| 68 | Py_DECREF(format_exception); |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | PyObject* ret_val = PyObject_CallFunctionObjArgs(format_exception, ptype, |
| 73 | pvalue, ptraceback, nullptr); |
| 74 | Py_DECREF(format_exception); |
| 75 | |
| 76 | if (!ret_val) { |
| 77 | return; |
| 78 | } |
| 79 | |
| 80 | if (!PyList_Check(ret_val)) { |
| 81 | Py_DECREF(ret_val); |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | Py_ssize_t n = PyList_GET_SIZE(ret_val); |
| 86 | for (Py_ssize_t i = 0; i < n; ++i) { |
| 87 | PyObject* v = PyList_GET_ITEM(ret_val, i); |
| 88 | #if PY_MAJOR_VERSION < 3 |
| 89 | strings::StrAppend(out, PyString_AS_STRING(v), "\n"); |
| 90 | #else |
| 91 | strings::StrAppend(out, PyUnicode_AsUTF8(v), "\n"); |
| 92 | #endif |
| 93 | } |
| 94 | |
| 95 | // Iterate through ret_val. |
| 96 | Py_DECREF(ret_val); |
| 97 | } |
| 98 | |
| 99 | string PyExceptionFetch() { |
| 100 | CHECK(PyErr_Occurred()) |
no test coverage detected