在 Go 中,如何将函数的标准输出捕获到字符串中?

新手上路,请多包涵

例如,在 Python 中,我可以执行以下操作:

 realout = sys.stdout
sys.stdout = StringIO.StringIO()
some_function() # prints to stdout get captured in the StringIO object
result = sys.stdout.getvalue()
sys.stdout = realout

你能在 Go 中做到这一点吗?

原文由 Andres Riofrio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 726
2 个回答

我同意你应该使用 fmt.Fprint 功能,如果你能管理的话。但是,如果您不控制要捕获其输出的代码,则可能没有该选项。

Mostafa 的答案有效,但如果你想在没有临时文件的情况下进行,你可以使用 os.Pipe 。这是一个与 Mostafa 的示例等效的示例,其中包含一些受 Go 测试包启发的代码。

 package main

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

func print() {
    fmt.Println("output")
}

func main() {
    old := os.Stdout // keep backup of the real stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    print()

    outC := make(chan string)
    // copy the output in a separate goroutine so printing can't block indefinitely
    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    // back to normal state
    w.Close()
    os.Stdout = old // restoring the real stdout
    out := <-outC

    // reading our temp stdout
    fmt.Println("previous output:")
    fmt.Print(out)
}

原文由 Evan Shaw 发布,翻译遵循 CC BY-SA 3.0 许可协议

这个答案与之前的答案类似,但通过使用 io/ioutil 看起来更清晰。

http://play.golang.org/p/fXpK0ZhXXf

 package main

import (
  "fmt"
  "io/ioutil"
  "os"
)

func main() {
  rescueStdout := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  fmt.Println("Hello, playground") // this gets captured

  w.Close()
  out, _ := ioutil.ReadAll(r)
  os.Stdout = rescueStdout

  fmt.Printf("Captured: %s", out) // prints: Captured: Hello, playground
}

原文由 mattes 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题