rust - Check if a command is in PATH/executable as process -


i want execute external program via std::process::command::spawn. furthermore want know reason why spawning process failed: because given program name doesn't exist/is not in path or because of different error?

example code of want achieve:

match command::new("rustc").spawn() {     ok(_) => println!("was spawned :)"),     err(e) => {         if /* ??? */ {             println!("`rustc` not found! check path!")         } else {             println!("some strange error occurred :(");         }     },  } 

when try execute program isn't on system, get:

error { repr: os { code: 2, message: "no such file or directory" } } 

but don't want rely on that. there way determine if program exists in path?

you can use e.kind() find errorkind error was.

match command::new("rustc").spawn() {     ok(_) => println!("was spawned :)"),     err(e) => {         if let notfound = e.kind() {             println!("`rustc` not found! check path!")         } else {             println!("some strange error occurred :(");         }     },  } 

edit: didn't find explicit documentation error kinds can returned, looked source code. seems error returned straight os. relevant code seems in src/libstd/sys/[unix/windows/..]/process.rs. snippet unix version:

one more edit: on second thought, i'm not sure if licenses allows posting parts of rust sources here, can see on github

which returns error::from_raw_os_err(...). windows version seemed more complicated, , couldn't find returns errors from. either way, seems you're @ mercy of operating system regarding that. @ least found following test in src/libstd/process.rs:

same above: github

that seems guarantee errorkind::notfound should returned @ least when binary not found. makes sense assume os wouldn't give notfound error in other cases, knows. if want absolutely sure program not found, you'll have search directories in $path manually. like:

use std::env; use std::fs;  fn is_program_in_path(program: &str) -> bool {     if let ok(path) = env::var("path") {         p in path.split(":") {             let p_str = format!("{}/{}", p, program);             if fs::metadata(p_str).is_ok() {                 return true;             }         }     }     false }  fn main() {     let program = "rustca"; // shouldn't found     if is_program_in_path(program) {         println!("yes.");     } else {         println!("no.");     } } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -