小编典典

在Go中,如何将函数的标准输出捕获到字符串中?

go

例如,在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中执行此操作吗?


阅读 270

收藏
2020-07-02

共1个答案

小编典典

我同意,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)
}
2020-07-02