go持续获取命令或程序返回值
获取njmon每3秒返回一次的结果,可以用回调进行结果处理
package main
import (
"bufio"
"log"
"os/exec"
)
func main() {
Exec("./njmon", "-s", "3", "-c", "1000")
}
func Exec(name string, args ...string) error {
cmd := exec.Command(name, args...)
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
log.Println("exec the cmd ", name, " failed")
return err
}
// 正常
outScan := bufio.NewScanner(stdout)
go func() {
for outScan.Scan() {
log.Println(outScan.Text())
}
}()
errScan := bufio.NewScanner(stderr)
for errScan.Scan() {
s := errScan.Text()
log.Println(s)
}
// 等待命令执行完
cmd.Wait()
return nil
}
以下参考:https://www.jb51.net/article/174623.htm
func Exec(name string, args ...string) error {
cmd := exec.Command(name, args...)
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
log.Println("exec the cmd ", name, " failed")
return err
}
// 正常日志
logScan := bufio.NewScanner(stdout)
go func() {
for logScan.Scan() {
log.Println(logScan.Text())
}
}()
// 错误日志
errBuf := bytes.NewBufferString("")
scan := bufio.NewScanner(stderr)
for scan.Scan() {
s := scan.Text()
log.Println("build error: ", s)
errBuf.WriteString(s)
errBuf.WriteString("\n")
}
// 等待命令执行完
cmd.Wait()
if !cmd.ProcessState.Success() {
// 执行失败,返回错误信息
return errors.New(errBuf.String())
}
return nil
}