Rust 简单的Command的操作

578 阅读1分钟

在 Rust 编程语言中,Command是标准库中的一个结构体,位于 std::process::Command 模块中。 Command 结构体用于创建和执行外部命令。 通过Command 结构体,你可以指定要执行的命令、命令的参数以及其他执行环境相关的设置,然后使用 spawn 方法来执行这个命令。这是 Rust 标准库中用于处理进程管理的一部分。

以下是一个简单的操作,使用Command来执行外部命令

use std::process::Command;
fn main() {
// 创建一个 Command 结构体,指定要执行的命令和参数
    let mut cmd = Command::new("ls");
    cmd.arg("-l"); // 添加命令参数
    
    // 执行命令并获取输出 
    let output = cmd.output().expect("failed to execute process"); 
    
    // 将命令输出转换成字符串并打印出来 
    println!("{}", String::from_utf8_lossy(&output.stdout));
}

我们也可以封装结构体

// 这是一种实时获取log的cmd操作
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
pub struct LogCats{ 
    adb_logcat:Child
}

impl LogCats{
    pub fn new() ->Self{
        let adb_logcat = Command::new("adb")
            .arg("logcat")
            .stdout(Stdio::piped()) // 将标准输出重定向到管道 
            .spawn() // 启动子进程 
            .expect("failed to execute adb logcat");
            
        LogCats{ adb_logcat } }
    }
    pub fn get_child_output(self) { 
        let stdout = self.adb_logcat.stdout.expect("failed to capture stdout");
        // 使用 BufReader 逐行读取输出 
        let reader = BufReader::new(stdout);
        for line in reader.lines() {
            match line { 
                Ok(line) => { 
                    // 这里处理每一行的输出 
                    let res= format!("ok:{}",line); 
                    ...
                    ...
                } 
                Err(e) => { eprintln!("Error reading line: {}", e); } 
            } 
        } 
    }
    pub fn kill_child(mut self) { 
        let _k= self.adb_logcat.kill(); 
    }
}
// 调用结构体
LogCats::new().get_child(clone_win); 
LogCats::new().kill_child();
// 通过Result返回的cmd操作 
pub fn use_cmd(args:Vec<String>)->Result<String,String>{ 
    let output =Command::new("cmd").args(args).output; 
    match output{ 
        Ok(child){ 
            if child.status.success(){ 
                let stdout = String::from_utf8_lossy(&child.stdout).to_string(); 
                Ok(stdout) 
            }else{
                let stderr = String::from_utf8_lossy(&child.stderr).to_string(); 
                Err(stderr) 
            }
        }
        Err(err)=>Err(format!("{}",err)) 
    } 
}