Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Created December 29, 2014 16:41
Show Gist options
  • Save mindscratch/0faa78bd3c0005d080bf to your computer and use it in GitHub Desktop.
Save mindscratch/0faa78bd3c0005d080bf to your computer and use it in GitHub Desktop.
capture stdout in golang
import (
"bytes"
"io"
"os"
)
// not thread safe
func captureStdout(f func()) string {
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
os.Stdout = old
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
@mindscratch
Copy link
Author

@thediveo
Copy link

thediveo commented May 5, 2020

Terrible: will simply block f() when it has reached the buffering capacity of the OS pipe.

@mindscratch
Copy link
Author

Terrible: will simply block f() when it has reached the buffering capacity of the OS pipe.

Suggestions on how to fix it?

@thediveo
Copy link

thediveo commented May 8, 2020

https://stackoverflow.com/a/10476304 demonstrates using io.Copy in a Go routine to keep the pipe flowing. Also does a clean shutdown and value return via channel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment