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条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?