简体   繁体   English

如何在 Rust 中获取 std::process::Command 后面的命令?

[英]How to get the command behind std::process::Command in Rust?

I'm passing around instances ofstd::process::Command .我正在传递std::process::Command的实例。 Before executing a command I'd like to log the entire command.在执行命令之前,我想记录整个命令。 For instance, if I'm given a command instance that has been constructed like that:例如,如果给我一个这样构造的command实例:

let command = Command::new("sh")
    .arg("-c")
    .arg("echo hello")

I would like to write a log message like:我想写一条日志消息,例如:

Executing command: 'sh' '-c' 'echo hello'

The API looks quite limited though.不过,API 看起来非常有限。 Is there a way to accomplish that?有没有办法做到这一点?

Debug is implemented for Command . Command实现了Debug

use std::process::Command;

fn main() {
    let mut command = Command::new("ls");
    command.arg("-l");
    println!("{:?}", command);
}

Output: "ls" "-l" Output: "ls" "-l"

You would like to get access to private fields in the command struct.您想访问command结构中的私有字段。 Private fields are not accessible by design.通过设计无法访问私有字段。

However, when a Debug trait has been implemented for the struct, the private members are 'printed' using the {:?} format option.但是,当为结构实现了 Debug 特征时,使用{:?}格式选项“打印”私有成员。

To access those private members programmatically, use the format!() macro.要以编程方式访问这些私有成员,请使用format!()宏。 This returns a std::String and accepts the {:?} formatting option.这将返回一个std::String并接受{:?}格式化选项。 This only works because the Debug trait has been implemented for Command.这只是因为已经为 Command 实现了 Debug trait。

fn main() {
    let mut command = Command::new("ls");
    command.arg("-l");
    let command_string: String = std::format!("{:?}", command);

    // Print the command_string to standard output 
    println!("cmd: {}", command_string);

    // split the command string accordinig to whitespace
    let command_parts = command_string.split(' ');

    // print the individual parts of the command_string
    for (index, part) in command_parts.enumerate() {
        println!("part[{}]: {}", index, part);
    }
}

Output: Output:

$> test_prog
   cmd: "ls" "-l"
   part[0]: "ls"
   part[1]: "-l"
$>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM