dqd2800 2018-01-14 19:17
浏览 318
已采纳

在Go中实时打印exec命令中的stdout [重复]

I have a small Go tool which basically allows the user to define an command that than will be run using os/exec.

My problem is that I want to show the user the output (stdout/stderr) of the command.

An example could look like this: The user defines a command that in the end is sh test.sh. Content of test.sh:

echo "Start"
sleep 7s
echo "Done"

With my current implementation the user can only see the output once the complete command finished. In the example above the user wouldn't see the output Start until the sleep command and the second echo finish.

I currently retrieve the output of the command like this:

cmd := exec.Command(command, args...)
cmd.Dir = dir
// Attach to the standard out to read what the command might print
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Panic(err)
}
// Execute the command
if err := cmd.Start(); err != nil {
    log.Panic(err)
}

buf := new(bytes.Buffer)
buf.ReadFrom(stdout)
log.Print(buf.String())

Is it somehow possible to read the stdout/stderr in real-time. Meaning that as soon as the user defined command creates and output it is printed?

</div>
  • 写回答

1条回答 默认 最新

  • duanlu4371 2018-01-14 19:42
    关注

    Thank you mh-cbon. That pushed me in the right direction.

    The code now looks like this and does exactly what I want it to do. I also found that when I use Run() instead of Start() the execution of the program only continues after the command has finished.

    cmd := exec.Command(command, args...)
    cmd.Dir = dir
    
    var stdBuffer bytes.Buffer
    mw := io.MultiWriter(os.Stdout, &stdBuffer)
    
    cmd.Stdout = mw
    cmd.Stderr = mw
    
    // Execute the command
    if err := cmd.Run(); err != nil {
        log.Panic(err)
    }
    
    log.Println(stdBuffer.String())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测