Goで標準出力をキャプチャする
·1 分で読めます
こんな感じかなぁ。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)
}アンダースタンディング コンピュテーション―単純な機械から不可能なプログラムまで
- 作者: Tom Stuart,笹田耕一(監訳),笹井崇司
- 出版社/メーカー: オライリージャパン
- 発売日: 2014/09/18
- メディア: 大型本
- この商品を含むブログ (5件) を見る
関連記事
GoLangでJavaのenumっぽいライブラリ作った話
2014-12-07
Macでファイルが変更されたら自動的にgofmtをかける
2014-10-21
Goでnilなsliceやmapを返すと空のsliceやmapになる
2014-09-15