1

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?

2 Answers 2

3

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"

2
  • But there is no way of accessing the command parts manually to have control over formatting?
    – bluenote10
    Apr 11, 2020 at 10:09
  • I'd simplified the problem for the question, in my use case I wanted to programmatically access the command fragments. This doesn't seem possible. I'll accept the answer, but man, what an unfortunate omission in the API.
    – bluenote10
    Apr 11, 2020 at 14:20
0

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"
$>
1
  • This doesn't work in general, split(' ') can split on spaces in arguments. You'd need to properly re-parse the string, accounting for quoting -- quite ugly.
    – bluenote10
    Apr 11, 2020 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.