执行任何 bash 命令,立即获取 stdout/stderr 的结果并使用标准输入
Execute any bash command, get the results of stdout/stderr immediatly and use stdin
我想执行任何 bash 命令。我找到 Command::new
但我无法执行 "complex" 命令,例如 ls ; sleep 1; ls
。此外,即使我将它放在 bash 脚本中并执行它,我也只会在脚本末尾得到结果(如流程文档中所述)。我希望在命令打印结果后立即获得结果(并且能够读取输入),就像我们在 bash.
中所做的一样
Command::new
确实是要走的路,但它是为了执行一个程序。 ls ; sleep 1; ls
不是程序,它是某些 shell 的指令。如果你想执行类似的事情,你需要请 shell 为你解释:
Command::new("/usr/bin/sh").args(&["-c", "ls ; sleep 1; ls"])
// your complex command is just an argument for the shell
获取输出有两种方式:
output
方法正在阻塞,returns 命令的输出和退出状态。
spawn
method is non-blocking, and returns a handle containing the child's process stdin
, stdout
and stderr
so you can communicate with the child, and a wait
方法等待它干净地退出。请注意,默认情况下,子文件继承其父文件描述符,您可能希望改为设置管道:
你应该使用类似的东西:
let child = Command::new("/usr/bin/sh")
.args(&["-c", "ls sleep 1 ls"])
.stderr(std::process::Stdio::null()) // don't care about stderr
.stdout(std::process::Stdio::piped()) // set up stdout so we can read it
.stdin(std::process::Stdio::piped()) // set up stdin so we can write on it
.spawn().expect("Could not run the command"); // finally run the command
write_something_on(child.stdin);
read(child.stdout);
我想执行任何 bash 命令。我找到 Command::new
但我无法执行 "complex" 命令,例如 ls ; sleep 1; ls
。此外,即使我将它放在 bash 脚本中并执行它,我也只会在脚本末尾得到结果(如流程文档中所述)。我希望在命令打印结果后立即获得结果(并且能够读取输入),就像我们在 bash.
Command::new
确实是要走的路,但它是为了执行一个程序。 ls ; sleep 1; ls
不是程序,它是某些 shell 的指令。如果你想执行类似的事情,你需要请 shell 为你解释:
Command::new("/usr/bin/sh").args(&["-c", "ls ; sleep 1; ls"])
// your complex command is just an argument for the shell
获取输出有两种方式:
output
方法正在阻塞,returns 命令的输出和退出状态。spawn
method is non-blocking, and returns a handle containing the child's processstdin
,stdout
andstderr
so you can communicate with the child, and await
方法等待它干净地退出。请注意,默认情况下,子文件继承其父文件描述符,您可能希望改为设置管道:
你应该使用类似的东西:
let child = Command::new("/usr/bin/sh")
.args(&["-c", "ls sleep 1 ls"])
.stderr(std::process::Stdio::null()) // don't care about stderr
.stdout(std::process::Stdio::piped()) // set up stdout so we can read it
.stdin(std::process::Stdio::piped()) // set up stdin so we can write on it
.spawn().expect("Could not run the command"); // finally run the command
write_something_on(child.stdin);
read(child.stdout);