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

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

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

问题

我知道如何捕获exec.Command的输出,但我也想将其流式传输到stdout并同时捕获它。谢谢任何建议!

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os/exec"
  6. )
  7. func main() {
  8. cmd := exec.Command("ls")
  9. var out bytes.Buffer
  10. cmd.Stdout = &out
  11. cmd.Run()
  12. fmt.Println(out.String())
  13. }

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

英文:

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!

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os/exec"
  6. )
  7. func main() {
  8. cmd := exec.Command("ls")
  9. var out bytes.Buffer
  10. cmd.Stdout = &out
  11. cmd.Run()
  12. fmt.Println(out.String())
  13. }

答案1

得分: 3

  1. package main
  2. import (
  3. "io"
  4. "os"
  5. "bytes"
  6. "fmt"
  7. "os/exec"
  8. )
  9. func main() {
  10. cmd := exec.Command("ls")
  11. var out bytes.Buffer
  12. w := io.MultiWriter(os.Stdout, &out)
  13. cmd.Stdout = w
  14. fmt.Printf("===标准输出:===\n")
  15. cmd.Run()
  16. fmt.Printf("\n===变量:===\n")
  17. fmt.Println(out.String())
  18. }
  1. <details>
  2. <summary>英文:</summary>
  3. ### Example using [`io.MultiWriter`][3]
  4. ```go
  5. package main
  6. import (
  7. &quot;io&quot;
  8. &quot;os&quot;
  9. &quot;bytes&quot;
  10. &quot;fmt&quot;
  11. &quot;os/exec&quot;
  12. )
  13. func main() {
  14. cmd := exec.Command(&quot;ls&quot;)
  15. var out bytes.Buffer
  16. w := io.MultiWriter(os.Stdout, &amp;out)
  17. cmd.Stdout = w
  18. fmt.Printf(&quot;===Stdout:===\n&quot;)
  19. cmd.Run()
  20. fmt.Printf(&quot;\n===Variable:===\n&quot;)
  21. fmt.Println(out.String())
  22. }

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:

确定