如何在Windows中输出PyErr_Print或将其保存为字符串

时间:2014-06-24 12:36:23

标签: c++ python-embedding

我正在编写嵌入式python解释器,有一个函数PyErr_Print()https://docs.python.org/3/c-api/exceptions.html)写入标准错误文本,解释为什么我调用的C函数失败。

这似乎不适用于Windows,因为它从不向终端写入任何内容,有没有办法将其重定向到某个地方,或者存储为字符串以便我可以看到它?

1 个答案:

答案 0 :(得分:2)

这是使用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
}