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

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

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问