DEV Community

chrischtel
chrischtel

Posted on

1

How to invoke system commands using in Rust

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!");
}
Enter fullscreen mode Exit fullscreen mode

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 with stdin/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 the spawn 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");
}
Enter fullscreen mode Exit fullscreen mode

For more examples visit the offical docs

I hope I could help you and you like my post.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
xenonpy profile image
XenonPydev • Edited

Just what I was looking for. However, inspecting the first code block:

use std::process::command;
Enter fullscreen mode Exit fullscreen mode

should be

use std::process::Command;
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Retry later