我如何在windows中获得PyErr_Print的输出或将其保存为字符串?
How can I get output of PyErr_Print in windows or save it as a string
我正在编写嵌入式python解释器,有一个函数PyErr_Print()
(https://docs.python.org/3/c-api/exceptions.html),它写入标准错误文本,解释为什么我调用的C函数失败。
这似乎在windows上不起作用,因为它从不向终端写入任何内容,是否有办法将其重定向到某个地方,或者存储为字符串以便我可以看到它?
下面是使用boost::python:
的解决方案#include <ostream>
#include <boost/python.hpp>
std::ostream& operator<<(std::ostream& os, boost::python::error_already_set& e) {
using namespace boost::python;
// acquire the Global Interpreter Lock
PyObject * extype, * value, * traceback;
PyErr_Fetch(&extype, &value, &traceback);
if (!extype) return os;
object o_extype(handle<>(borrowed(extype)));
object o_value(handle<>(borrowed(value)));
object o_traceback(handle<>(borrowed(traceback)));
object mod_traceback = import("traceback");
object lines = mod_traceback.attr("format_exception")(
o_extype, o_value, o_traceback);
for (int i = 0; i < len(lines); ++i)
os << extract<std::string>(lines[i])();
// PyErr_Fetch clears the error state, uncomment
// the following line to restore the error state:
// PyErr_Restore(extype, value, traceback);
// release the GIL
return os;
}
像这样使用:
#include <iostream>
#include <boost/python.hpp>
try {
// some code that raises
catch (boost::python::error_already_set& e) {
std::cout << e << std::endl; // or stream to somewhere else
}
相关文章:
- 我将如何保存此 for 循环的输出
- 在 C++ 的文本文件中保存多个输出
- 如何以C++格式输出已保存.html文件中<a href>标签中的所有链接?
- 创建一个动态数组,包括汽车的年份和品牌,但无法保存我的第一个输出
- 文件不会将输出保存到文件中,并在 Linux C++奇怪地打印出一个字符串
- 将所有控制台输出数据保存到新的文本文件C++
- 如何将输出从终端保存到变量
- 在 C++ 中将编辑过的内文件保存到输出文件时出现问题
- 使用Borland C++执行dos命令并保存输出
- C++ 在退出 WINAPI 之前将控制台输出保存到文本文件(无 MFC)
- 旋转纹理 sfml 并将输出保存到文件
- 使用十六进制保存输出会增加空格
- c++将输出(数字)保存到一个数组中.一次两个数字
- 在运行时保存服务的输出
- 我如何在windows中获得PyErr_Print的输出或将其保存为字符串?
- 从.txt读取int,将其保存到vector,然后保存到输出文件
- c++ Qt和WinExec -保存CMD输出文件在特定的文件夹
- 使用FMOD将输出保存到磁盘
- 如何将C++控制台输出保存在文本文件中
- 写入文件时,只有最后一行保存到我的输出文件中