在Go中,如何将函数的stdout捕获到字符串中?

例如,在Python中,我可以执行以下操作:


realout = sys.stdout

sys.stdout = StringIO.StringIO()

some_function() # prints to stdout get captured in the StringIO object

result = sys.stdout.getvalue()

sys.stdout = realout

您可以在Go中执行此操作吗?


慕姐4208626
浏览 280回答 3
3回答

三国纷争

我同意,fmt.Fprint只要可以管理,就应该使用这些功能。但是,如果您不控制要捕获其输出的代码,则可能没有该选项。Mostafa的答案有效,但是如果您想在没有临时文件的情况下进行操作,则可以使用os.Pipe。这是一个与Mostafa等效的示例,其中一些代码受Go的测试包的启发。package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "os")func print() {&nbsp; &nbsp; fmt.Println("output")}func main() {&nbsp; &nbsp; old := os.Stdout // keep backup of the real stdout&nbsp; &nbsp; r, w, _ := os.Pipe()&nbsp; &nbsp; os.Stdout = w&nbsp; &nbsp; print()&nbsp; &nbsp; outC := make(chan string)&nbsp; &nbsp; // copy the output in a separate goroutine so printing can't block indefinitely&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; var buf bytes.Buffer&nbsp; &nbsp; &nbsp; &nbsp; io.Copy(&buf, r)&nbsp; &nbsp; &nbsp; &nbsp; outC <- buf.String()&nbsp; &nbsp; }()&nbsp; &nbsp; // back to normal state&nbsp; &nbsp; w.Close()&nbsp; &nbsp; os.Stdout = old // restoring the real stdout&nbsp; &nbsp; out := <-outC&nbsp; &nbsp; // reading our temp stdout&nbsp; &nbsp; fmt.Println("previous output:")&nbsp; &nbsp; fmt.Print(out)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go