dpwu16132 2017-04-26 13:26
浏览 141

连续读取exec.Cmd输出

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 
", output.String())  // script is writing but nothing can be read from output
   cmd.Wait()
   fmt.Printf(" After Wait %s 
", output.String())  // if we wait to finish execution, we can read all output
}
  • 写回答

2条回答 默认 最新

  • douliangbian7323 2017-04-26 16:27
    关注

    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")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端