Created
December 29, 2014 16:41
-
-
Save mindscratch/0faa78bd3c0005d080bf to your computer and use it in GitHub Desktop.
capture stdout in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Terrible: will simply block f() when it has reached the buffering capacity of the OS pipe.
Terrible: will simply block f() when it has reached the buffering capacity of the OS pipe.
Suggestions on how to fix it?
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
http://craigwickesser.com/post/capture-stdout-in-go/