如何捕获stdout输出,同时显示进度



我有一个名为print()的函数,它每2秒打印一次数字,这个函数在goroutine中运行。

我需要将它的stdout打印传递给一个变量并打印它,但不是一次,直到它完成
我需要在一个无限循环中有一个扫描仪,它将扫描stdout并打印它,一旦函数完成,扫描仪也将完成。

我试着用这个答案,但它没有打印任何内容
这就是我尝试做的:

package main
import (
"bufio"
"fmt"
"os"
"sync"
"time"
)

func print() {
for i := 0; i < 50; i++ {
time.Sleep(2 * time.Second)
fmt.Printf("hello number: %dn", i)
}
}
func main() {
old := os.Stdout // keep backup of the real stdout
defer func() { os.Stdout = old }()
r, w, _ := os.Pipe()
os.Stdout = w
go print()

var wg sync.WaitGroup
c := make(chan struct{})
wg.Add(1)

defer wg.Done()
for {
<-c
scanner := bufio.NewScanner(r)
for scanner.Scan() {
m := scanner.Text()
fmt.Println("output: " + m)
}
}
c <- struct{}{}
wg.Wait()
fmt.Println("DONE")
}  

我也试着用io.Copy来读取缓冲区,但它也不起作用:

package main
import (
"bytes"
"fmt"
"io"
"os"
"time"
)

func print() {
for i := 0; i < 50; i++ {
time.Sleep(2 * time.Second)
fmt.Printf("hello number: %dn", i)
}
}
// https://blog.kowalczyk.info/article/wOYk/advanced-command-execution-in-go-with-osexec.html
func main() {
old := os.Stdout // keep backup of the real stdout
defer func() { os.Stdout = old }()
r, w, _ := os.Pipe()
os.Stdout = w
go print()
fmt.Println("DONE 1")
outC := make(chan string)
for {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
out := <-outC
fmt.Println("output: " + out)
}
// back to normal state
w.Close()

fmt.Println("DONE")
}

可以将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: %dn", 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)
}
}

相关内容

最新更新