1 回答
TA贡献1951条经验 获得超3个赞
可以print()作为“黑盒”运行并捕获其输出,尽管它有点棘手并且不适用于 Go Playground。
package main
import (
"bufio"
"fmt"
"os"
"runtime"
"time"
)
func print() {
for i := 0; i < 50; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Printf("hello number: %d\n", i)
}
}
func main() {
var ttyName string
if runtime.GOOS == "windows" {
fmt.Println("*** Using `con`")
ttyName = "con"
} else {
fmt.Println("*** Using `/dev/tty`")
ttyName = "/dev/tty"
}
f, err := os.OpenFile(ttyName, os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer f.Close()
r, w, _ := os.Pipe()
oldStdout := os.Stdout
os.Stdout = w
defer func() {
os.Stdout = oldStdout
fmt.Println("*** DONE")
}()
fmt.Fprintln(f, "*** Stdout redirected")
go func(){
print()
w.Close()
r.Close()
}()
c := make(chan struct{})
go func(){c <- struct{}{}}()
defer close(c)
<-c
scanner := bufio.NewScanner(r)
for scanner.Scan() {
m := scanner.Text()
fmt.Fprintln(f, "output: " + m)
}
}
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报