如果cmd.Stdout已被更改,则由cmd.StdoutPipe()返回的io.ReadCloser会导致恐慌。

时间:2019-06-17 16:28:29

标签: go io

我想解析外部命令的标准输出。为此,我像这样使用exec.StdoutPipe

func main() {
    // ...
    cmd := exec.Command(commandString)
    stdoutIn, _ := cmd.StdoutPipe()
    cmd.Start()
    go monitorCommand(stdoutIn, watchphrase)
    // ...
}

func monitorCommand(output io.ReadCloser, watchphrase string) {
    scanner := bufio.NewScanner(output)
    go func() {
        for scanner.Scan() {
            sText := scanner.Text()
            if strings.Contains(sText, watchphrase) {
                break
            }
        }
    }()
    // ...
}

现在,我还想将命令Stdout设置为io.Writer。为此,我将上面的代码修改如下:

    // ...
    cmd := exec.Command(commandString)
    cmd.Stdout = debugText
    stdoutIn, _ := cmd.StdoutPipe()
    // ...

但是此更改导致它陷入惊慌scanner.Scan()


panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x18 pc=0x5e4f1c] goroutine 178 [running]:
bufio.(*Scanner).Scan(0xc0009e2000, 0xc0001e3fc0) C:/Go/src/bufio/scan.go:213 +0x7c
main.monitorCommand.func1(0xc0009e2000, 0xc000057240, 0x5, 0xc0002bc000) C:/Users/jakob/Documents/projects/F1/F1viewer/main.go:229
created by main.monitorCommand C:/Users/jakob/Documents/projects/F1/F1viewer/main.go:228 +0x104

没有迹象表明更改cmd.Stdout应该影响the godoc中的cmd.StdoutPipe()

0 个答案:

没有答案