douweng7233
douweng7233
2018-09-27 21:30

如何在仍然实时登录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 dongzouqie4220 3年前

    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().

    点赞 评论 复制链接分享

相关推荐