例如,在 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 中做到这一点吗?
最佳答案
我同意你应该使用 fmt.Fprint
功能,如果你可以管理它。但是,如果您不控制要捕获其输出的代码,则可能没有该选项。
Mostafa 的回答有效,但如果你想在没有临时文件的情况下这样做,你可以使用 os.Pipe .这是一个与 Mostafa 等效的示例,其中包含一些受 Go 测试包启发的代码。
package main
import (
"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)
}
关于go - 在 Go 中,如何将函数的标准输出捕获到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473800/