bluenote10
bluenote10

Reputation: 26530

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

I'm passing around instances of 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:

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. Is there a way to accomplish that?

Upvotes: 1

Views: 999

Answers (2)

Gardener
Gardener

Reputation: 2660

You would like to get access to private fields in the command struct. 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.

To access those private members programmatically, use the format!() macro. This returns a std::String and accepts the {:?} formatting option. This only works because the Debug trait has been implemented for Command.

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:

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

Upvotes: 0

justinas
justinas

Reputation: 6857

Debug is implemented for Command.

use std::process::Command;

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

Output: "ls" "-l"

Upvotes: 3

Related Questions