关于语法错误的 Python 异常文本(Boost 库)
我有这个代码 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);
...
}
程序尝试执行的文件有语法错误,因此引发异常。当程序尝试获取错误消息时崩溃...
该代码可以很好地处理运行时错误,但会因语法错误而崩溃。
我如何获取此类错误的错误字符串?
提前致谢
I've got this code snnipet (the whole program compiles and links correctly):
...
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);
...
}
The file that the program tries to execute has a syntax error, so an exception is thrown. When the program tries to get the error message crashes...
The code works well with run-time errors but somehow crashes with syntax errors.
How can i get the error string with this kind of errors?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 PyErr_Fetch 文档:“值和回溯对象可能为 NULL即使类型对象不是“。在尝试提取值之前,您应该检查 pvalue 是否为 NULL。
如果要检查异常是否是 SyntaxError,可以将 ptype 与列出的异常类型进行比较 这里。
为了更具体地回答,我需要从崩溃点开始回溯。
编辑
pvalue 是一个异常对象,而不是 str 实例,因此您应该使用 PyObject_Str 获取异常的字符串表示形式。
您可能需要首先调用 PyErr_NormalizeException 将 pvalue 转换为正确的异常类型。
From the documentation of PyErr_Fetch: "The value and traceback object may be NULL even when the type object is not". You should check whether pvalue is NULL or not before trying to extract the value.
If you want to check whether the exception is a SyntaxError you can compare ptype against the exception types listed here.
To answer anymore specifically I would need a backtrace from the point where it crashed.
Edit
pvalue is an exception object, not a str instance so you should use PyObject_Str to get the string representation of the exception.
You may need to call PyErr_NormalizeException first to turn pvalue into the correct exception type.