如何从 Rust 进程内部重定向 stderr?
How to redirect stderr from inside the process in Rust?
我正在尝试从进程内部重定向 Stderr
文件描述符,但似乎没有实现它,而且我没有看到类似于 [=12= 的任何内容的明确路径] 来自 C/C++。
我试过:
- 直接实现
Read
(impl Read for Stderr
),但要覆盖整个代码库。
消费文件描述符中的数据,然后进入File
,然后进入ReadBuf
trait FDReader {
fn consume(&mut self);
}
impl FDReader for Stderr {
fn consume(&mut self) {
let f = std::fs::File::from_raw_fd(self.as_raw_fd());
let mut extract = String::new();
BufReader::new(f).read_to_string(&mut extract);
}
}
我专注于 consume
,因为在测试我的代码时我不需要完全 return 任何东西,尽管这没有用。
由于我运行在Linux系统上,我不打算发布代码,我也考虑过重定向/proc/self/fd/2 -> /dev/null
然后return 当我想写到那里时的原始指针引用。对于这个范围来说,这太过分了。
我也想直接使用libc::dup2
——尽管我已经厌倦了。
标准库中无法做到这一点1。 gag crate 允许将 stderr 或 stdout 重定向到文件或什么都不重定向,但它只适用于 *nix 系统。
从另一个角度看问题,我建议您完全不要直接使用 stdout 或 stderr。相反,使用 依赖注入 传递可以写入的值。不要使用 println
,而是使用 writeln
.
另请参阅:
1 这严格来说 不正确。您是否注意到 stdout and stderr are not output during tests? That's because the compiler (and the test suite) make use of a pair of unstable, hidden functions 允许更改 stdout 和 stderr 的线程本地实例。
另请参阅:
- Why doesn't println! work in Rust unit tests?
我正在尝试从进程内部重定向 Stderr
文件描述符,但似乎没有实现它,而且我没有看到类似于 [=12= 的任何内容的明确路径] 来自 C/C++。
我试过:
- 直接实现
Read
(impl Read for Stderr
),但要覆盖整个代码库。 消费文件描述符中的数据,然后进入
File
,然后进入ReadBuf
trait FDReader { fn consume(&mut self); } impl FDReader for Stderr { fn consume(&mut self) { let f = std::fs::File::from_raw_fd(self.as_raw_fd()); let mut extract = String::new(); BufReader::new(f).read_to_string(&mut extract); } }
我专注于
consume
,因为在测试我的代码时我不需要完全 return 任何东西,尽管这没有用。由于我运行在Linux系统上,我不打算发布代码,我也考虑过重定向
/proc/self/fd/2 -> /dev/null
然后return 当我想写到那里时的原始指针引用。对于这个范围来说,这太过分了。
我也想直接使用libc::dup2
——尽管我已经厌倦了。
标准库中无法做到这一点1。 gag crate 允许将 stderr 或 stdout 重定向到文件或什么都不重定向,但它只适用于 *nix 系统。
从另一个角度看问题,我建议您完全不要直接使用 stdout 或 stderr。相反,使用 依赖注入 传递可以写入的值。不要使用 println
,而是使用 writeln
.
另请参阅:
1 这严格来说 不正确。您是否注意到 stdout and stderr are not output during tests? That's because the compiler (and the test suite) make use of a pair of unstable, hidden functions 允许更改 stdout 和 stderr 的线程本地实例。
另请参阅:
- Why doesn't println! work in Rust unit tests?