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

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

问题描述

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

  realout = sys.stdout 
sys。 stdout = StringIO.StringIO()
some_function()#打印到stdout获取在StringIO对象中捕获
result = sys.stdout.getvalue()
sys.stdout = realout

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

解决方案

我同意你应该使用 fmt.Fprint 函数,如果你可以管理的话。然而,如果你不控制你捕获的输出的代码,你可能没有这个选项。



Mostafa的答案很有用,但如果你想这样做的话没有临时文件,您可以使用 os.Pipe 。这是一个相当于Mostafa的例子,其中一些代码受到了Go的测试包的启发。

 包主

导入(
字节
fmt
io
os


func print(){
fmt.Println(output)
}

func main(){
old:= os.Stdout //保留实际标准输出的备份
r ,w,_:= os.Pipe()
os.Stdout = w

print()

outC:= make(chan string)
//在单独的goroutine中复制输出以便打印不能无限制地阻止
去func(){
var buf bytes.Buffer
io.Copy(& buf,r)
outC < - buf.String()
()

//回到正常状态
w.Close()
os.Stdout =旧的//恢复真正的stdout
out:=< -outC

//读取我们的临时标准输出
fmt.Println(previous output:)
fmt.Print(out)
}


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

Can you do this in Go?

解决方案

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'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天全站免登陆