Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to check if an executable exists for `std::process::Command`?

I want to create a std::process::Command and check whether an executable actually exists at that location before actually spawning the Command later. What would be the pragmatic way to do this?

I have this code:

let c = std::process::Command::new("my_exe");
// something here
c.spawn().unwrap();

I want to be able to validate the my_exe path when creating the Command and then spawn way later.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to check if a file is present in the working directory, you can use Path::exists, as described in How to check whether a path exists?.

Also, Command::spawn() takes a mutable reference to self so c needs to be mutable.

use std::path::Path;
use std::process::Command;

if Path::new("PATH_TO_EXECUTABLE").exists() {
    let mut c = Command::new("PATH_TO_EXECUTABLE");
    // do something
    c.spawn().unwrap();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading