如何从 Rust 进程内部重定向 stderr?

How to redirect stderr from inside the process in Rust?

我正在尝试从进程内部重定向 Stderr 文件描述符,但似乎没有实现它,而且我没有看到类似于 [=12= 的任何内容的明确路径] 来自 C/C++。

我试过:

我也直接使用libc::dup2——尽管我已经厌倦了。

标准库中无法做到这一点1gag 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?