gpt4 book ai didi

c++ - 将标准输出重定向到 ostream

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:52 25 4
gpt4 key购买 nike

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

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

我可以重定向 cout这样通过使用 rdbuf()但是printf()print()来自 python 未重定向,因为它转到 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;
}

关于c++ - 将标准输出重定向到 ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com