<p>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 ?</p>
<pre><code>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
}
</code></pre>
<hr/>**评论:**<br/><br/>chstelic: <pre><p>maybe you could try <code>cmd.StdoutPipe</code> and <code>cmd.StderrPipe</code> instead which return <code>io.ReadCloser</code> instance, then you can read from them</p>
<p>because of streaming nature of pipe, goroutines would come into picture here.</p>
<p>hope this will give you some idea</p></pre>ugizashinje: <pre><p>thanks mate, it worked with
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]))
}
}</p></pre>ariacode: <pre><p>See <a href="https://github.com/boz/ephemerald/blob/master/lifecycle/action_exec.go#L130-L163" rel="nofollow">here</a>. You can run goroutines which read stdout and stderr. Be sure to read until <code>io.EOF</code> before calling <code>cmd.Wait()</code>.</p>
<p>There is some documentation on this <a href="https://golang.org/pkg/os/exec/#Cmd.StdoutPipe" rel="nofollow">here</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传