dousi6192 2018-02-22 12:05
浏览 434
已采纳

将stdout流写入文件

I am running an external process via exec.Command() and I want the stdout from the command to be printed as well as written to file, in real time (similar to using tee from a command-line) .

I can achieve this with a scanner and a writer:

cmd := exec.Command("mycmd")
cmdStdOut, _ := cmd.StdoutPipe()

s := bufio.NewScanner(cmdStdOut)
f, _ := os.Create("stdout.log")
w := bufio.NewWriter(f)

go func() {
    for s.Scan(){
        t := s.Text()
        fmt.Println(t)
        fmt.Fprint(w, t)
        w.Flush()    
    }
}

Is there a more idiomatic way to do this that avoids clobbering Scan and Flush?

  • 写回答

1条回答 默认 最新

  • doucheng8471 2018-02-22 12:37
    关注

    Assign a multiwriter to the commmand's stdout that writes to a file and to a pipe. You can then use the pipe's read end to follow the output.

    This example behaves similar to the tee tool:

    package main
    
    import (
        "io"
        "os"
        "os/exec"
    )
    
    func main() {
        var f *os.File // e.g. os.Create, os.Open
    
        r, w := io.Pipe()
        defer w.Close()
    
        cmd := exec.Command("mycmd")
        cmd.Stdout = io.MultiWriter(w, f)
    
        // do something with the output while cmd is running by reading from r
        go io.Copy(os.Stdout, r) 
    
        cmd.Run()
    }
    

    Alternative with StdoutPipe:

    package main
    
    import (
        "io"
        "os"
        "os/exec"
    )
    
    func main() {
        var f *os.File
    
        cmd := exec.Command("date")
        stdout, _ := cmd.StdoutPipe()
    
        go io.Copy(io.MultiWriter(f, os.Stdout), stdout)
    
        cmd.Run()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝