如何将os.Stdout输出复制到字符串变量 [英] How to copy os.Stdout output to string variable

查看:50
本文介绍了如何将os.Stdout输出复制到字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的功能:

package main

import (
    "fmt"
)

// PrintSomething prints some thing
func PrintSomething() {
    fmt.Println("print something")
}

func main() {
    PrintSomething()
}

如何将PrintSomething包装到另一个调用CaptureSomething的函数中,以将字符串"print something"保存到变量中并返回它?

How do I wrap PrintSomething to another function call CaptureSomething to save the string "print something" to a variable and return it?

推荐答案

创建管道并设置 stdout 到管道编写器.启动goroutine将管道读取器复制到缓冲区.完成后,关闭管道编写器并等待goroutine完成读取.以字符串形式返回缓冲区.

Create pipe and set stdout to the pipe writer. Start a goroutine to copy the pipe reader to a buffer. When done, close the pipe writer and wait for goroutine to complete reading. Return the buffer as a string.

// capture replaces os.Stdout with a writer that buffers any data written 
// to os.Stdout. Call the returned function to cleanup and get the data
// as a string.
func capture() func() (string, error) {
    r, w, err := os.Pipe()
    if err != nil {
        panic(err)
    }

    done := make(chan error, 1)

    save := os.Stdout
    os.Stdout = w

    var buf strings.Builder

    go func() {
        _, err := io.Copy(&buf, r)
        r.Close()
        done <- err
    }()

    return func() (string, error) {
        os.Stdout = save
        w.Close()
        err := <-done
        return buf.String(), err
    }

}

像这样使用它:

done := capture()
fmt.Println("Hello, playground")
capturedOutput, err := done()
if err != nil {
    // handle error
}

游乐场示例

这篇关于如何将os.Stdout输出复制到字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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