将标准输出重定向到ostream
Redirect stdout to 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;
}
相关文章:
- 如何将stdout重定向到stderr
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- Windows C++重定向库
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 使用 dup2() 进行输入重定向
- 将 clangd stderr 重定向到文件而不是控制台
- 如何在C++中获取重定向网页的URL
- 将标准输出重定向到ostream
- 如何撤消此代码上的 cin 重定向?
- 使用重定向标准处理子进程中的 kbhit
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 如何将HTTPS流量重定向到本地主机:443上的代理?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 尝试在 Windows 上重定向 stdout 和 stderr——_fileno(stdout) 返回 -2
- 可以将Boost消息队列文件重定向到用户指定的位置
- 在程序执行期间从标准输出重定向到自定义流
- 如何在c++和linux中将std::ostream重定向到文件或/dev/null
- 如何将 ostream 重定向到提升日志库