When developing programs, we often need to make external calls to other programs (like command line exes). This can be done with Command in Rust.
We can chain function calls, and pass arguments to a command with arg()
and args. The syntax for invoking command line executables is elegant in Rust.
To begin, suppose we want to execute the cwebp.exe program which encodes WebP images. The executable is located at the root of the Windows C directory.
new()
call, specify in the path to the exe as the string
argument to new()
.arg()
repeatedly, or call args()
with a string
array.use std::process::Command; fn main() { // Run cwebp with 4 arguments. Command::new("c:\\cwebp.exe") .args(&["-q", "50", "c:\\programs\\yield.png", "-o", "c:\\programs\\yield.webp"]) .output() .expect("failed to execute process"); println!("DONE"); }DONE
Suppose we try to launch an exe on the system, but the exe is not present. This will cause an error to occur—and the program will exit.
if
-statement. The inner code of the if will be reached if an error occurs.if
-statement.use std::process::Command; fn main() { // Handle missing file. if let Err(e) = Command::new("c:\\missing.exe") .arg("?") .output() { println!("{:?}", e); } }Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }
Handling external processes in Rust is done often. With Command new, we can invoke exe programs and handle errors that occur as this happens.