小编Pra*_*ant的帖子

如何检索SyntaxError的filename和lineno属性

我在我的应用程序中嵌入了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); …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

8
推荐指数
1
解决办法
1255
查看次数

标签 统计

python ×1

python-3.x ×1