CPython-打印回溯

时间:2019-06-03 16:03:26

标签: python c++ cpython

如何在CPython中将回溯对象转换为其字符串表示形式? 我试过了,但是输出不是很有用。

    PyObject *type, *value, *traceback;
    PyErr_Fetch(&type, &value, &traceback);

    PyObject* strTrace = PyObject_Repr(traceback);
    pyStrTrace = PyUnicode_AsEncodedString(strTrace, "utf-8", "strict");
    Py_XDECREF(strTrace);
    const char* sTrace = PyBytes_AS_STRING(pyStrTrace);

sTrace的内容:

 <traceback object at 0x000002594A5CC598>

1 个答案:

答案 0 :(得分:0)

有一条评论建议导入traceback python模块,该模块当然可以很好地工作,但是我更喜欢仅使用C ++的解决方案,因此我提出了此代码段。希望有人发现它有用。

if (PyTraceBack_Check(traceback))
{
    PyTracebackObject* traceRoot = (PyTracebackObject*)traceback;
    PyTracebackObject* pTrace = traceRoot;

    while (pTrace != NULL)
    {
        PyFrameObject* frame = pTrace->tb_frame;
        PyCodeObject* code = frame->f_code;

        int lineNr = PyFrame_GetLineNumber(frame);
        const char *sCodeName = PyUnicode_AsUTF8(code->co_name);
        const char *sFileName = PyUnicode_AsUTF8(code->co_filename);

        printf("at %s (%s:%d); ", sCodeName, sFileName, lineNr);
        pTrace = pTrace->tb_next;
    }        
}