如何将os.Exec中的stdout传送到文件和终端?

如何将os.Exec中的stdout传送到文件和终端?

问题描述:

How to pipe stdout for os.Exec to file but also to terminal?

I've try this:

go func() {
    scanner := bufio.NewScanner(stdout)
    writer := bufio.NewWriter(logFile)
    for scanner.Scan() {
        log.Debugln(scanner.Text())
        writer.WriteString(scanner.Text())
    }
    writer.Flush()
}()

But writer.WriteString(scanner.Text()) losts in file. How to got them back? Maybe there is some more elegant solution with pipes?

如何将os.Exec的stdout通过管道传输到文件,也可以传输到终端? p>

我已经尝试过: p>

  go func(){
扫描器:= bufio.NewScanner(stdout)
 writer  := bufio.NewWriter(logFile)
用于扫描器.Scan(){
 log.Debugln(scanner.Text())
 writer.WriteString(scanner.Text())
} 
 writer.Flush(  )
}()
  code>  pre> 
 
 

但是 writer.WriteString(scanner.Text()) code>丢失了 code >在文件中。 如何找回他们? 也许有一些更优雅的管道解决方案? p> div>

Create a io.MultiWriter with arguments os.Stdout and the file. Set Cmd.Stdout to the multiwriter. Run the command.

 cmd := exec.Command(name, args...)
 cmd.Stdout = io.MultiWriter(os.Stdout, file)
 err := cmd.Run()

If you want to write line by line to log.Debugf and other files, then do the following:

go func() {
    scanner := bufio.NewScanner(stdout)
    writer := bufio.NewWriter(io.MultiWriter(os.Stdout, file))
    for scanner.Scan() {
        log.Debugln(scanner.Text())
        writer.Write(scanner.Bytes())
        writer.WriteByte('
')  // add line separator
    }
    writer.Flush()
}()

This code assumes that the line separator in the input is .