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

将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 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题