In Go, how do I capture stdout of a function into a string?

后端 未结 4 571
庸人自扰
庸人自扰 2020-11-28 06:13

In Python, for example, I can do the following:

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


        
4条回答
  •  星月不相逢
    2020-11-28 06:32

    This answer is similar to the previous ones but looks cleaner by using 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
    }
    

提交回复
热议问题