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

huangapple go评论74阅读模式
英文:

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())
}

我会将代码翻译为中文并返回给你。

英文:

I know how to capture the output of a exec.Command but I would like to also stream it to stdout while still capturing it.
Thanks for any input!

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())
}

答案1

得分: 3

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("===标准输出:===\n")
    cmd.Run()
    fmt.Printf("\n===变量:===\n")
    fmt.Println(out.String())
}

<details>
<summary>英文:</summary>

### Example using [`io.MultiWriter`][3]

```go
package main

import (
    &quot;io&quot;
    &quot;os&quot;
    &quot;bytes&quot;
    &quot;fmt&quot;
    &quot;os/exec&quot;
)

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

huangapple
  • 本文由 发表于 2022年4月13日 22:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/71859079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定