在 Go 中,如何将函数的 stdout 捕获到字符串中? [英] In Go, how do I capture stdout of a function into a string?

查看:30
本文介绍了在 Go 中,如何将函数的 stdout 捕获到字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python, for example, I can do the following:

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

Can you do this in Go?

推荐答案

我同意你应该使用 fmt.Fprint 函数,如果你可以管理它.但是,如果您不控制要捕获其输出的代码,则可能没有该选项.

I agree you should use the fmt.Fprint functions if you can manage it. However, if you don't control the code whose output you're capturing, you may not have that option.

Mostafa 的答案有效,但如果您想在没有临时文件的情况下进行操作,您可以使用 os.Pipe.这是一个与 Mostafa 等效的示例,其中一些代码受 Go 的测试包启发.

Mostafa's answer works, but if you want to do it without a temporary file you can use os.Pipe. Here's an example that's equivalent to Mostafa's with some code inspired by Go's testing package.

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 中,如何将函数的 stdout 捕获到字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆