如何在Go中获得系统命令的输出? [英] How do you get the output of a system command in Go?
本文介绍了如何在Go中获得系统命令的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
使用 exec.Run 通过指定管道作为标准输出(如果需要,还可以使用stderr)。它将返回cmd,其中包含Stdout(和Stderr)字段中的 os.File 。然后,您可以使用例如 ioutil.ReadAll 阅读它。
示例:
包主
导入(
exec;
io / ioutil;
)
func main(){
if cmd,e:= exec.Run(/ bin / ls,nil,nil,exec.DevNull,exec.Pipe,exec.MergeWithStdout); e == nil {
b,_:= ioutil.ReadAll(cmd.Stdout)
println(output:+ string(b))
}
}
Let's say I want to run 'ls' in a go program, and store the results in a string. There seems to be a few commands to fork processes in the exec and os packages, but they require file arguments for stdout, etc. Is there a way to get the output as a string?
解决方案
Use exec.Run by specifying Pipe as the stdout (and stderr if you want). It will return cmd, which contains an os.File in the Stdout (and Stderr) fields. Then you can read it using for example ioutil.ReadAll.
Example:
package main
import (
"exec";
"io/ioutil";
)
func main() {
if cmd, e := exec.Run("/bin/ls", nil, nil, exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil {
b, _ := ioutil.ReadAll(cmd.Stdout)
println("output: " + string(b))
}
}
这篇关于如何在Go中获得系统命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文