Home > Back-end >  Get output of system command in Rust
Get output of system command in Rust

Time:03-29

I'am trying to execute a shell command on Rust in Unix environement, so i tried the following:

use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::prelude::CommandExt;
use std::process::Command;
pub fn main() {
       let mut command = Command::new("ls");
       println!("Here is your result : {:?}", command.output().unwrap().stdout);
}

I obtain a list of u8, and i'am wondering how can i get list of my file items? And is it a simpler method to do so ? Thanks :)

CodePudding user response:

You can convert the stdout to a String object like this:

use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::prelude::CommandExt;
use std::process::Command;
use std::str;

pub fn main() {
    let mut command = Command::new("ls");
    let output = command.output().unwrap();
    
    println!("{}", str::from_utf8(&output.stdout[..]).unwrap());
}
  • Related