英文:
stream stdout from other program without for loop
问题
我有一个程序,它编译和运行另一个程序,并将stdout管道传递给自身以进行打印,因为那个程序不会终止,所以我需要流式传输它的stdout。
// 省略了样板代码
func stream(stdoutPipe io.ReadCloser) {
buffer := make([]byte, 100, 1000)
for ;; {
n, err := stdoutPipe.Read(buffer)
if err == io.EOF {
stdoutPipe.Close()
break
}
buffer = buffer[0:n]
os.Stdout.Write(buffer)
}
}
func main() {
command := exec.Command("go", "run", "my-program.go")
stdoutPipe, _ := command.StdoutPipe()
_ = command.Start()
go stream(stdoutPipe)
do_my_own_thing()
command.Wait()
}
它可以工作,但是如何在不使用循环重复检查的情况下实现相同的功能?是否有一个库函数可以做同样的事情?
英文:
I have a program that compile and run another program and pipe the stdout to itself for printing, since that program doesn't terminate so I need to stream it's stdout
// boilerplate ommited
func stream(stdoutPipe io.ReadCloser) {
buffer := make([]byte, 100, 1000)
for ;; {
n, err := stdoutPipe.Read(buffer)
if err == io.EOF {
stdoutPipe.Close()
break
}
buffer = buffer[0:n]
os.Stdout.Write(buffer)
}
}
func main() {
command := exec.Command("go", "run", "my-program.go")
stdoutPipe, _ := command.StdoutPipe()
_ = command.Start()
go stream(stdoutPipe)
do_my_own_thing()
command.Wait()
}
It works, but how do I do the same without repeatedly checking with a for loop, is there a library function that does the same thing?
答案1
得分: 12
您可以给exec.Cmd
提供一个io.Writer
作为标准输出。您自己的程序用于标准输出的变量(os.Stdout
)也是一个io.Writer
。
command := exec.Command("go", "run", "my-program.go")
command.Stdout = os.Stdout
command.Start()
command.Wait()
英文:
You can give the exec.Cmd
an io.Writer
to use as stdout. The variable your own program uses for stdout (os.Stdout
) is also an io.Writer
.
command := exec.Command("go", "run", "my-program.go")
command.Stdout = os.Stdout
command.Start()
command.Wait()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论