我同意,
fmt.Fprint只要可以管理,就应该使用这些功能。但是,如果您不控制要捕获其输出的代码,则可能没有该选项。
Mostafa的答案有效,但是如果您想在没有临时文件的情况下进行操作,则可以使用os.Pipe。这是一个与Mostafa等效的示例,其中一些代码受Go的测试包的启发。
package mainimport ( "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)}


