使用exec.Command
执行后, 可以等命令执行结束后, 一次性获取所有输出.
也可以在命令执行的同时, "实时地"获取其输出.
下边的代码演示了两种获取输出的方式.
由于是在windows上执行, 引入了golang.org/x/text/encoding/simplifiedchinese
来解决乱码问题(不得不说中国的程序员真的累, 学啥编程语言都要解决这种问题).
package main
import (
"bufio"
"fmt"
"os/exec"
"golang.org/x/text/encoding/simplifiedchinese"
)
func getOutputDirectly(name string, args ...string) (output []byte) {
cmd := exec.Command(name, args...)
output, err := cmd.Output() // 等到命令执行完, 一次性获取输出
if err != nil {
panic(err)
}
output, err = simplifiedchinese.GB18030.NewDecoder().Bytes(output)
if err != nil {
panic(err)
}
return
}
func getOutputContinually(name string, args ...string) (output chan []byte) {
cmd := exec.Command(name, args...)
output = make(chan []byte, 10240)
defer close(output)
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
defer stdoutPipe.Close()
go func() {
scanner := bufio.NewScanner(stdoutPipe)
for scanner.Scan() { // 命令在执行的过程中, 实时地获取其输出
data, err := simplifiedchinese.GB18030.NewDecoder().Bytes(scanner.Bytes()) // 防止乱码
if err != nil {
fmt.Println("transfer error with bytes:", scanner.Bytes())
continue
}
fmt.Printf("%s\n", string(data))
}
}()
if err := cmd.Run(); err != nil {
panic(err)
}
return
}
func main() {
// 效果: 等一会儿, 打印出所有输出
output1 := getOutputDirectly("tree")
fmt.Printf("%s\n", output1)
// 不断输出, 直到结束
output2 := getOutputContinually("tree")
for o := range output2 {
fmt.Printf("%s\n", o)
}
}
欢迎补充指正!