如何将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?

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 .