如何检索SyntaxError的filename和lineno属性

Pra*_*ant 8 python python-3.x

我在我的应用程序中嵌入了python解释器.我用它来运行使用PyRun_String()API的python脚本.PyErr_Fetch()如果遇到错误/异常,我可以使用获取错误信息.这给了我异常类型,异常值和异常回溯.然后我从traceback中找到原始错误的行号.但是,在语法错误的情况下,我不会得到任何类型的回溯.有人知道如何检索行号而无需追溯..?有没有办法使用异常类型或异常值来检索它.?

Python文档声明:

此类的实例具有filename,lineno,offset和text属性,以便于访问详细信息.异常实例的str()仅返回消息.

如何在嵌入式python中检索SyntaxError的filename和lineno属性?

任何帮助将不胜感激.提前致谢.


谢谢你的建议Brett.但我已经通过使用PyObject_GetAttr()尝试了它.

请参阅下面用于测试目的的示例代码.

int main(int argc, char** argv)
{
    Py_Initialize();

    // Get a reference to the main module.
    PyObject* main_module =
        PyImport_AddModule("__main__");

    // Get the main module's dictionary
    // and make a copy of it.
    PyObject* main_dict =
        PyModule_GetDict(main_module);

    const char *script_source = "def main():\n\tprint('Hello'\n\nmain()";

    PyObject *res = PyRun_String(script_source,Py_file_input,main_dict,main_dict);
    if(res == NULL)
    {
        PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
        PyErr_Fetch(&ptype,&pvalue,&ptraceback);

        PyObject* py_filename = PyUnicode_FromString("filename");
        PyObject* file_name = PyObject_GetAttr(ptype,py_filename);

        PyObject* py_lineno = PyUnicode_FromString("lineno");
        PyObject* line_no = PyObject_GetAttr(ptype,py_lineno);
    }
}
Run Code Online (Sandbox Code Playgroud)

我故意在script_source中插入语法错误.

我无法从file_name和line_no对象中检索实际的文件名和行号.

我尝试调试file_name和line_no对象,内容如下所示."语法错误对象的成员文件名"和"语法错误对象的成员行号"

这些对象不可调用,所以我不能使用PyObject_Call()变体.

有没有什么方法可以从这些对象中获取实际的文件名和行号..?

在这个文件名中将是我正在使用PyRun_String().

Bre*_*non 1

这些属性在PySyntaxErrorObject struct上设置,但请注意,如果您遵循 Python 的稳定 ABI,则不会公开该结构。否则,您应该能够使用PyObject_GetAttr* 函数来获取属性。