Subscribed unsubscribe Subscribe Subscribe

oinume journal

Scratchpad of what I learned

Goで標準出力をキャプチャする

こんな感じかなぁ。http://play.golang.org/p/2DFtYAsFO9

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

type Capturer struct {
    saved         *os.File
    bufferChannel chan string
    out           *os.File
    in            *os.File
}

// 標準出力をキャプチャする
func (c *Capturer) StartCapturingStdout() {
    c.saved = os.Stdout
    var err error
    c.in, c.out, err = os.Pipe()
    if err != nil {
        panic(err)
    }

    os.Stdout = c.out
    c.bufferChannel = make(chan string)
    go func() {
        var b bytes.Buffer
        io.Copy(&b, c.in)
        c.bufferChannel <- b.String()
    }()
}

// キャプチャを停止する
func (c *Capturer) StopCapturingStdout() string {
    c.out.Close()
    os.Stdout = c.saved
    return <-c.bufferChannel
}

func main() {
    c := &Capturer{}
    c.StartCapturingStdout()
    fmt.Println("hello")

    captured := c.StopCapturingStdout()
    fmt.Println("captured:", captured)
}