dongqi19827 2012-05-06 19:59
浏览 208
已采纳

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

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?

  • 写回答

4条回答 默认 最新

  • dskzap8756 2012-05-07 03:21
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题