不断从exec.Cmd输出读取 [英] continuously reading from exec.Cmd output
本文介绍了不断从exec.Cmd输出读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
package主要
导入(
fmt
os / exec
字节
os
)
func main(){
cmd:= exec.Command(scripts / long_script)
输出:= new(bytes.Buffer)
cmd.Stdout =输出
cmd。 Stderr =输出
if err:= cmd.Start(); err!= nil {//在Start程序继续执行并且脚本在后台执行
fmt.Printf(Failed to start+ err.Error())
os.Exit(1)
$ b fmt.Printf(Before WAIT%s \\\
,output.String())//脚本正在写入,但没有任何内容可以从输出读取
cmd.Wait()
fmt.Printf(After Wait%s \\\
,output.String())//如果我们等待完成执行,我们可以读取所有输出
}
$ c $最终我设法用[]字节做到这一点 $ b 解决方案 $ b
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()
如果cmd.ProcessState.Success(){。 // ProcessState设置在Wait
之后fmt.Println(Script success)
} else {
fmt.Println(脚本失败)
}
Guys I am trying pick new lines as they come from command output, but always I end up doing it synchronous way (I have to wait until script is finished). I tired to use fsnotify but it is working only with regular files, do you have any idea how it can be done ?
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
}
解决方案 eventually I managed to do it with []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")
}
这篇关于不断从exec.Cmd输出读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文