我使用下面的代码可以正常工作,但是在某些情况下,该过程卡住了,并且看不到任何输出。例如,这段代码运行npm install
或mvn clean install
,并且在大多数情况下运行良好,但有时会挂起,而您没有得到任何输出
func exec(stdout io.reader,stderr io.reader) (*bufio.Scanner,*bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanerr := bufio.NewScanner(stderr)
scanout.Split(bufio.ScanRunes)
for scanout.Scan() {
fmt.Print(scanout.Text())
}
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
return scanout,scanerr
}
现在,如果我像下面那样更改顺序(先犯错,然后是stdout),则在命令挂起时会收到一些错误输出,但是我看不到在线输出,在运行命令时会看到一些输出,并且在完成时你看剩下的了。您可以等待2分钟或更长时间的输出,然后在该过程结束时立即获得长输出。
如何解决我将能够使输出联机并在流程挂起时获得一些反馈的情况?
func exec(stdout io.reader,*bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanerr := bufio.NewScanner(stderr)
scanout.Split(bufio.ScanRunes)
for scanout.Scan() {
fmt.Print(scanout.Text())
}
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}
return scanout,scanerr
}
更新
应该是这样吗?
func exec(stdout io.reader,*bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
}()
go func() {
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}()
}