执行任何bash命令,立即获得stdout/stderr的结果并使用stdin [英] Execute any bash command, get the results of stdout/stderr immediatly and use stdin
问题描述
我想执行任何bash命令.我找到了Command::new
,但无法执行"ls ; sleep 1; ls
"之类的复杂"命令.而且,即使我将其放在bash脚本中并执行它,我的结果也只会在脚本的末尾(如流程文档中所述).我希望在命令打印出结果(并能够读取输入)后立即获得结果,就像在bash中执行结果一样.
I would like to execute any bash command. I found Command::new
but I'm unable to execute "complex" commands such as ls ; sleep 1; ls
. Moreover, even if I put this in a bash script, and execute it, I will only have the result at the end of the script (as it is explain in the process doc). I would like to get the result as soon as the command prints it (and to be able to read input as well) the same way we can do it in bash.
推荐答案
Command::new
确实是可行的方法,但它意在执行程序. ls ; sleep 1; ls
不是程序,它是某些shell的说明.如果您想执行类似的操作,则需要询问一个shell来为您解释:
Command::new
is indeed the way to go, but it is meant to execute a program. ls ; sleep 1; ls
is not a program, it's instructions for some shell. If you want to execute something like that, you would need to ask a shell to interpret that for you:
Command::new("/usr/bin/sh").args(&["-c", "ls ; sleep 1; ls"])
// your complex command is just an argument for the shell
要获得输出,有两种方法:
To get the output, there are two ways:
- the
output
method is blocking and returns the outputs and the exit status of the command. - the
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
method to wait for it to cleanly exit. Note that by default the child inherits its parent file descriptor and you might want to set up pipes instead:
您应使用类似以下内容的
You should use something like:
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命令,立即获得stdout/stderr的结果并使用stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!