关于语法错误的 Python 异常文本(Boost 库)

jab*_*jab 1 c++ python exception boost-python

我有这个代码 snnipet (整个程序正确编译和链接):

...
try
{
    boost::python::exec_file(
        "myscript.py",            // this file contains a syntax error
        my_main_namespace, 
        my_local_namespace
    );
    return true;
}
catch(const boost::python::error_already_set &)
{
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);

    // the next line crashes on syntax error
    std::string error = boost::python::extract<std::string>(pvalue);
    ...
}
Run Code Online (Sandbox Code Playgroud)

程序尝试执行的文件存在语法错误,因此引发异常。当程序尝试获取错误消息时崩溃...

该代码可以很好地处理运行时错误,但会因语法错误而崩溃。

我如何获取此类错误的错误字符串?

提前致谢

And*_*son 5

来自PyErr_Fetch 的文档:“即使类型对象不是,值和回溯对象也可能为 NULL”。在尝试提取值之前,您应该检查 pvalue 是否为 NULL。

std::string error;
if(pvalue != NULL) {
    error = boost::python::extract<std::string>(pvalue);
}
Run Code Online (Sandbox Code Playgroud)

如果您想检查异常是否是 SyntaxError,您可以将 ptype 与此处列出的异常类型进行比较。

为了更具体地回答,我需要从崩溃点开始回溯。

编辑

pvalue 是一个异常对象,而不是 str 实例,因此您应该使用PyObject_Str来获取异常的字符串表示形式。

您可能需要首先调用PyErr_NormalizeException将 pvalue 转换为正确的异常类型。