If you want to invoke system commands in your Rust program, you need to make use of the std::process::Command
module. In this short post, i'll tell you how to use this module. For more infos on Rust you can visit the well documented Rust book
Getting started
We wanna make sure that we import the std::process::Command
module. To do that, go to your main.rs file.
use std::process::command;
fn main() {
println!("Hello World!");
}
spawn, output and status
Before we start invoking a system command, we must distinguish between three different methods to spawn a child process and run system commands.
spawn
-> Executes the commands as a child process and returns a handle to it. For more information on how to interact withstdin/stdout
check out this answer on stack overflow.
output
-> Runs the command as a child process and waits until the command finishes, then collects the output. If you want to print out the output of a command in real time, please refer to thespawn
method.
status
-> Runs a command as a child process and waits for it to finish and collect its status.
How to structure a command
We will use the command ls
as an example
use std::process:Command;
fn main(){
Command::new("ls")
.arg("-a")
.spawn()
.expect("failed to execute command");
}
For more examples visit the offical docs
I hope I could help you and you like my post.
Top comments (0)