Home
Rust
Command new Example (Start Exe)
This page was last reviewed on May 22, 2023.
Dot Net Perls
Command. 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.
Start exe. 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.
Start We create a new command with the new() call, specify in the path to the exe as the string argument to new().
Then To pass arguments to a command, we can either use arg() repeatedly, or call args() with a string array.
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
Handling errors. 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.
And To capture the error, we can use an if-statement. The inner code of the if will be reached if an error occurs.
Then We can print or otherwise handle the error if one occurs. If no error occurs, we never reach the inner part of the 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 22, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.