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

标签 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 中做到这一点吗?

最佳答案

我同意你应该使用 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/

相关文章:

go - 如何通过 http 提供静态文件

go - 为什么下面的 golang 程序会抛出运行时内存不足错误?

c++ - 可选择在运行时打印到标准输出

node.js - 错误 : write EPIPE when piping node output to "| head"

go - 执行大量 I/O 的 go 程序崩溃

go - 为什么在主goroutine终止后subgoroutine可以运行?

go - 将结构数组编码为没有父标记的 xml

eclipse - 在 Eclipse 中分离标准输入和标准输出文件

c - 在C中将当前目录中的所有文件列出为字符串

c - 如何使用 dup 和/或 dup2 将标准输出重定向到管道,然后输出到另一个管道,然后再返回到标准输出?