Home
Rust
Command new Example (Start Exe)
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen