我如何在windows中获得PyErr_Print的输出或将其保存为字符串?

How can I get output of PyErr_Print in windows or save it as a string

本文关键字:输出 保存 字符串 Print windows PyErr      更新时间:2023-10-16

我正在编写嵌入式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
}