在 Rust 中获取系统命令的输出

Get output of system command in Rust

我正在尝试在 Unix 环境中对 Rust 执行 shell 命令,所以我尝试了以下操作:

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);
}

我获得了 u8 的列表,我想知道如何获得我的文件项目的列表? 这是一种更简单的方法吗? 谢谢:)

您可以将 stdout 转换为字符串对象,如下所示:

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());
}