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

I agree you should use the fmt.Fprint functions if you can manage it. However, if you don’t control the code whose output you’re capturing, you may not have that option.

Mostafa’s answer works, but if you want to do it without a temporary file you can use os.Pipe. Here’s an example that’s equivalent to Mostafa’s with some code inspired by Go’s testing package.

package main

import (

func print() {

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


    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
    os.Stdout = old // restoring the real stdout
    out := <-outC

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

Leave a Comment