收到 Python/C API 的错误消息
getting a error message with Python/C API
我一直在寻找一种方法来获取在 C++ 中执行 python 代码时的错误消息。我尝试了 How to get Python exception text 的一些答案,但其中任何一个都对我有用。有人可以解释我做错了什么吗?
#include <iostream>
#include <Python.h>
int main() {
Py_Initialize();
if (PyRun_SimpleString("something stupid")) {
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
const char *errMsg = PyUnicode_AsUTF8(PyObject_Str(ptraceback));
std::cout << errMsg;
}
Py_Finalize();
}
我希望打印类似的内容:
File "<string>", line 1
something stupid
^
SyntaxError: invalid syntax
但是当我 运行 代码时,cout
打印:
<NULL>
根据文档 (https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleStringFlags),当使用 PyRun_SimpleStringFlags()
(或只是 PyRun_SimpleString()
)时:
If there was an error, there is no way to get the exception information.
所以代码必须运行换一种方式。最终,您可以 运行 在解释器中:
PyRun_SimpleString("import traceback, sys");
PyRun_SimpleString("trace = ''.join(traceback.format_exception(sys.last_type, sys.last_value, sys.last_traceback))");
然后从解释器中读取trace
,类似于此答案。
我一直在寻找一种方法来获取在 C++ 中执行 python 代码时的错误消息。我尝试了 How to get Python exception text 的一些答案,但其中任何一个都对我有用。有人可以解释我做错了什么吗?
#include <iostream>
#include <Python.h>
int main() {
Py_Initialize();
if (PyRun_SimpleString("something stupid")) {
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
const char *errMsg = PyUnicode_AsUTF8(PyObject_Str(ptraceback));
std::cout << errMsg;
}
Py_Finalize();
}
我希望打印类似的内容:
File "<string>", line 1
something stupid
^
SyntaxError: invalid syntax
但是当我 运行 代码时,cout
打印:
<NULL>
根据文档 (https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleStringFlags),当使用 PyRun_SimpleStringFlags()
(或只是 PyRun_SimpleString()
)时:
If there was an error, there is no way to get the exception information.
所以代码必须运行换一种方式。最终,您可以 运行 在解释器中:
PyRun_SimpleString("import traceback, sys");
PyRun_SimpleString("trace = ''.join(traceback.format_exception(sys.last_type, sys.last_value, sys.last_traceback))");
然后从解释器中读取trace
,类似于此答案