1use std::process::Command;
2
3pub struct CmdUtil;
12
13impl CmdUtil {
14
15 pub fn run_cmd(cmd: Vec<&str>) -> Result<(), String> {
20 if cmd.len() > 0 {
21 let mut c = Command::new(cmd[0]);
22 if cmd.len() > 1 {
23 c.args(&cmd[1..]);
24 }
25 let output = c.output().expect("请检查命令是否正确,或是否具备执行权限或环境变量等!");
27 if output.status.success() {
29 println!("命令执行成功!");
30 let stdout = String::from_utf8_lossy(&output.stdout);
32 println!("命令输出:\n{}", stdout);
33 } else {
34 println!("命令执行失败!");
35 let stderr = String::from_utf8_lossy(&output.stderr);
37 println!("错误信息:\n{}", stderr);
38 }
39 }
40 Ok(())
41 }
42
43 pub fn run_script(script_path: &str) -> std::io::Result<()> {
45 #[cfg(windows)]
46 let status = Command::new("cmd.exe")
47 .arg("/c")
48 .arg(script_path) .status()?;
50
51 #[cfg(not(windows))]
52 let status = Command::new("/bin/sh")
53 .arg(script_path) .status()?;
55
56 println!("脚本执行状态: {}", status);
57 Ok(())
58 }
59
60 pub fn run_script_with_params(script_path: &str, params: Vec<&str>) -> std::io::Result<()> {
62 #[cfg(windows)]
63 let status = Command::new("cmd.exe")
64 .arg("/c")
65 .arg(script_path) .args(¶ms)
67 .status()?;
68
69 #[cfg(not(windows))]
70 let status = Command::new("/bin/sh")
71 .arg(script_path) .args(¶ms)
73 .status()?;
74
75 println!("脚本执行状态: {}", status);
76 Ok(())
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn test_run_cmd() {
86 let cmd = vec!["cmd.exe", "/c", "cd", "/d", "d:/Environment/"];
94 let res = CmdUtil::run_cmd(cmd);
95 println!("{:?}", res);
96
97 let cmd = vec!["ffmpeg"];
98 let res = CmdUtil::run_cmd(cmd);
99 println!("{:?}", res);
100 }
101}