Search code examples
rustcommandgtk

Printing output of command


I'm using gtk-rs to take the value of an input and use it to execute a command with xdotool:

 input.connect_activate(clone!(@weak window => move |entry| {
    let input_text = entry.text();
    let cmd = format!(
        "xdotool search --onlyvisible --name {} windowactivate",
        input_text
    );

    let output = std::process::Command::new("sh")
        .arg("-c")
        .arg(cmd)
        .spawn()
        .unwrap();

    println!("{}", String::from_utf8_lossy(&output.stdout));

    window.close();
}));

I'm getting this compiling error:

error[E0308]: mismatched types
   --> src/main.rs:66:48
    |
66  |         println!("{}", String::from_utf8_lossy(&output.stdout));
    |                        ----------------------- ^^^^^^^^^^^^^^ expected slice `[u8]`, found enum `std::option::Option`
    |                        |
    |                        arguments to this function are incorrect
    |
    = note: expected reference `&[u8]`
               found reference `&std::option::Option<ChildStdout>`
note: associated function defined here
   --> /home/alex/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs:631:12
    |
631 |     pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
    |            ^^^^^^^^^^^^^^^

So I tried this:

match output.stdout {
    Some(stdout) => {
        println!("{}", String::from_utf8_lossy(&stdout));
    },
    None => {
        println!("No output");
    }
}

But I'm getting the same error.

Update:

I tried:

let output = std::process::Command::new("sh")
    .arg("-c")
    .arg(cmd)
    .output()
    .unwrap();

println!(Output: "{}", String::from_utf8_lossy(&output.stdout));

But nothing is being printed:

Output: 

Full code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ea4431b73191c132f4392378cce13604


Solution

  • After reading the comments and docs, I managed to print the command with:

    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
    

    But I had to do: xdotool search --onlyvisible --name {} because xdotool search --onlyvisible --name {} windowactivate prints nothing.