continuously reading from exec.Cmd output

xuanbao · · 481 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 ( &#34;fmt&#34; &#34;os/exec&#34; &#34;bytes&#34; &#34;os&#34; ) func main() { cmd := exec.Command(&#34;scripts/long_script&#34;) 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(&#34;Failed to start &#34; + err.Error()) os.Exit(1) } fmt.Printf(&#34; Before WAIT %s \n&#34;, output.String()) // script is writing but nothing can be read from output cmd.Wait() fmt.Printf(&#34; After Wait %s \n&#34;, 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 &gt; 0{ fmt.Printf(&#34;taken %d chars %s&#34;,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

481 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传