从exec.Cmd输出连续读取

时间:2017-04-26 13:26:54

标签: go exec stdout

伙计我正在尝试选择新行,因为它们来自命令输出,但总是我最终以同步方式执行(我必须等到脚本完成)。我厌倦了使用fsnotify,但它只适用于常规文件,你知道怎么做吗?

package main
import (
   "fmt"
   "os/exec"
   "bytes"
   "os"
)

func main() {
   cmd := exec.Command("scripts/long_script")
   output := new(bytes.Buffer)
   cmd.Stdout = output
   cmd.Stderr = output
   if err := cmd.Start(); err != nil{ // after Start program is continued and script is executing in background
     fmt.Printf("Failed to start " + err.Error())
     os.Exit(1)
   }
   fmt.Printf(" Before WAIT %s \n", output.String())  // script is writing but nothing can be read from output
   cmd.Wait()
   fmt.Printf(" After Wait %s \n", output.String())  // if we wait to finish execution, we can read all output
}

2 个答案:

答案 0 :(得分:4)

最终我设法用[] bytes

来做
stdout, err := cmd.StdoutPipe()
buff := make([]byte,10)
var n int
for err == nil {
    n,err = stdout.Read(buff)
    if n > 0{
        fmt.Printf("taken %d chars %s",n,string(buff[:n]))
    }
}
cmd.Wait()
if cmd.ProcessState.Success() {. // ProcessState is set after Wait
    fmt.Println("Script success")  
} else {
    fmt.Println("Script failed")
}

答案 1 :(得分:3)

您应该使用os.StdoutPipe()

func main() {
    for i := 10; i < 20; i++ {
        go printName(`My name is Bob, I am ` + strconv.Itoa(i) + ` years old`)
        // Adding delay so as to see incremental output
        time.Sleep(60 * time.Millisecond)
    }
    // Adding delay so as to let program complete
    // Please use channels or wait groups
    time.Sleep(100 * time.Millisecond)
}

func printName(jString string) {
    cmd := exec.Command("echo", "-n", jString)
    cmdReader, err := cmd.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    scanner := bufio.NewScanner(cmdReader)
    go func() {
        for scanner.Scan() {
            fmt.Println(scanner.Text())
        }
    }()
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }
    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }
}

帮助我的消息来源: nathanleclaire.com blog.kowalczyk.info