Home > Enterprise >  Command not found when using std::process::command in rust?
Command not found when using std::process::command in rust?

Time:10-09

So, i am getting this error when i run a command in linux terminal using std::process::Command. The part of the code is:

use std::process::Command;

fn main() {
    let mut playmusic = "mpv https://www.youtube.com/watch?v=kJQP7kiw5Fk";
    let status = Command::new(playmusic).status().expect("error status");    
}

The above code for the command, i found at rust docs. I tried everything in the docs, but none of them worked like using wait command.

Everytime i get this error:

thread 'main' panicked at 'error status: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:46:63

Since, the error says that the command not found, i ran it in my terminal but there it ran successfully. But, when using this in std::process::Command, it fails.

CodePudding user response:

It fails, because you are using it wrong. You want to exec program mpv with argument https://..., but you are currently telling rust to run program mpv https://..., which of course does not exist. Too pass arguments to programs use Command's method arg or args.

So your example can be fixed as such:

use std::process::Command;

fn main() {
    let url = "https://www.youtube.com/watch?v=kJQP7kiw5Fk";
    let status = Command::new("mpv")
        .arg(url)
        .status()
        .expect("Failed to run mpv");    
}

If you want to know why it is designed this way, it's because rust will call one of the exec syscalls. See exec(3) to understand how it works.

  • Related