将标准输出重定向到ostream



是否可以将stdout(不是cout!(重定向到流(ostream((不是文件!

为什么?我正在我的应用程序中集成一个 python 解释器,并希望从 python 代码中捕获print()调用。

我能够使用rdbuf()以这种方式重定向cout但 python 中的printf()print()没有重定向,因为它会转到stdout而不是cout

在 Linux 上,您可以在 python 脚本期间将 STDOUT 临时重定向到临时文件。

在 python 调用结束时,您可以读取临时文件的内容,然后转储该文件。

我很确定Windows会有类似的机制。

这是尝试一些 RAII 清理所有手柄的第一次尝试。

#include <unistd.h>
#include <cstdio>
#include <stdlib.h>
#include <string>
#include <iostream>
void simulate_python_script() {
std::printf("Written to STDOUT I think");
}
struct auto_fd {
auto_fd(int fd)
: fd_(fd) {}
~auto_fd() {
if (fd_ != -1)
::close(fd_);
}
auto_fd(auto_fd const&) = delete;
auto_fd& operator=(auto_fd const&) = delete;
operator int() const {
return fd_;
}
int fd_;
};
struct file_closer
{
void operator()(FILE* p) const noexcept
{
::fclose(p);
}
};

using auto_fp = std::unique_ptr<FILE, file_closer>;
auto make_auto_fp(FILE* fp)
{
return auto_fp(fp, file_closer());
}
struct push_fd {
push_fd(int target, int new_fd)
: saved_(::dup(target)), target_(target) {
::dup2(new_fd, target);
}
~push_fd() {
if (saved_ != -1) {
::dup2(saved_, target_);
::close(saved_);
}
}
int saved_, target_;
};
int main() {
using namespace std::literals;

auto tempfp = make_auto_fp(::tmpfile());
auto tempfd = auto_fd(::fileno(tempfp.get()));
// redirect STDOUT to the temp file with RAII
{
push_fd fd_save(1, tempfd);
simulate_python_script();
}
// now read the file which Python thought was STDOUT    
char buf[256];
while (auto count = ::read(tempfd, buf, 256)) {
if (count < 0) break; // error condition
std::cout.write(buf, count);
}
std::cout << std::endl;
}

最新更新