如何将缓冲区打印到标准输出但也捕获为字符串?

How to print buffer to stdout but also capture as string?

我知道如何捕获 exec.Command 的输出,但我还想在捕获它的同时将其流式传输到 stdout。 感谢您的任何输入!

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    cmd.Stdout = &out
    cmd.Run()
    fmt.Println(out.String())
}

示例使用 io.MultiWriter

package main

import (
    "io"
    "os"
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    w := io.MultiWriter(os.Stdout, &out)
    cmd.Stdout = w
    fmt.Printf("===Stdout:===\n")
    cmd.Run()
    fmt.Printf("\n===Variable:===\n")
    fmt.Println(out.String())
}