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

将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 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)