我正在尝试使用Command API启动进程并将其标准输出重定向到标准错误 . 以下失败:
Command::new("tput").arg("rc")
.stdout(io::stderr())
.status()
.expect("failed to run tput");
因为 Command::new("tput").arg("rc").stdout(<XXX>)
期望 std::process::Stdio
:
expected struct `std::process::Stdio`, found struct `std::io::Stderr`
Bash中的等价物可能是 tput rc > /dev/stderr
.
我想知道如何正确地做到这一点 .
1 回答
从Rust 1.15.0开始,
Stdio
不会在可移植API中公开此功能,但是您可以使用特定于平台的扩展特征来实现此目的 .在类Unix平台上,the std::os::unix::io::FromRawFd trait is implemented on Stdio . 此特征提供单个方法
from_raw_fd
,可以将文件描述符转换为实现特征的类型 . 由于标准错误被定义为文件描述符2,因此您只需使用.stdout(Stdio::from_raw_fd(2))
即可 .在Windows上,there's a similar trait called FromRawHandle implemented on Stdio . 不幸的是,它没有在在线文档中列出;它只包含特定于Unix的变体 . 您可以调用
GetStdHandle(STD_ERROR_HANDLE)
来获取标准错误的句柄 .