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

标签 c++ windows stream stdout

是否可以重定向 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/

相关文章:

C++ 链表值追溯改变

c++ - 这种无锁的dlist插入安全吗?

C++ 为什么 empty set::emplace() 将一个元素插入到一组指针中?

windows - 无效 ID : Process leaked file descriptors. Jenkins

windows - 有没有像PeekMessage这样不处理消息的函数?

IOS UI 在套接字连接期间卡住

c++ - 我的 List<T> 实现有什么问题?

windows - 如何知道平板电脑是 'Laptop'还是 'Tablet'模式

javascript - 在 Node.js/Gulp 中重用流管道/子管道

c - 在子进程中操作流