douweng7233 2018-09-27 21:30
浏览 185
已采纳

如何在仍然实时登录os.Stdout的同时解析exec.Command的输出?

In a small Go app I'm shelling out to run a command using the os/exec package. Currently I'm passing through the log output by setting:

cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err := cmd.Run()

What I'd like to do now is grab the output of the log (specifically the 2nd last line) and store that in a variable. I thought this would be as easy as changing err := cmd.Run() to cmdOutput, err := cmd.Output() and parsing the log string for the value I'm looking for - however this triggers an error saying exec: Stdout already set.

I could remove the setting of cmd.Stdout, but I would still like the rest of the log output to be passed through the current process the same way it is now.

I have control over the program that I am shelling out to as well, so if there's a better way to send a JSON snippet from a child command/process to the parent Go app other than writing a file to disk, that would work too.

Any help would be greatly appreciated - I'm a bit of a golang scrub...

  • 写回答

1条回答 默认 最新

  • dongzouqie4220 2018-09-27 21:52
    关注

    You can use io.MultiWriter together with bytes.Buffer for that:

    var errBuf, outBuf bytes.Buffer
    cmd.Stderr = io.MultiWriter(os.Stderr, &errBuf)
    cmd.Stdout = io.MultiWriter(os.Stdout, &outBuf)
    err := cmd.Run()
    

    This will still log to os.Stdout and os.Stderr, but you can use errBuf.Bytes() to get the error output and outBuf.Bytes() to get the normal output. outBuf.Bytes() will give you a byte slice equivalent to the one returned by cmd.Output().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本