我想重定向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。我需要做相反的事情。有可能吗?
发布于 2021-06-11 03:27:55
sys.stdout可以分配给任何包含write和flush方法的类实例。
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
}
https://stackoverflow.com/questions/67784850
复制相似问题