【问题标题】:How to redirect python stdout to log file by using pybind 11 in c++如何在 C++ 中使用 pybind 11 将 python stdout 重定向到日志文件
【发布时间】:2021-08-19 09:59:03
【问题描述】:

我想重定向 python stdout 以使用 pybind11 将其写入日志文件。

从 pybind11 文档中找到 py::scoped_ostream_redirect 方法。

我想做以下事情:

py::scoped_ostream_redirect stream(
    py::module_::import("sys").attr("stdout"),
    log()                               

); 

将标准输出重定向到 log(),其中 log 是一个 c++ 对象。

据我了解,scoped_ostream_redirect 用于将 c++ 流重定向到 python。我需要做相反的事情。有可能吗?

【问题讨论】:

    标签: python c++ object methods pybind11


    【解决方案1】:

    sys.stdout 可以分配给任何包含写入和刷新方法的类的实例。

    class Logger
    {
    public:
       void write(std::string str){
       // write here where you want to write the content of print function
           log.write(str);
       }
    
       void flush(){
           std::cout << std::flush();
       }
    }
    

    这里需要将类添加到python模块中。

    PYBIND11_EMBEDDED_MODULE(embeded, module) 
    {
        py::class_<LogWriter>(module, "Writer")
            .def("write", &Logger::write)
            .def("flush", &Logger::flush);
     }
    
    void main(){
        py::module::import("embedded");
        Logger logger;       
        py::module::import("sys").attr("stdout") = logger
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多