从其他程序中流式传输标准输出,而不使用for循环。

huangapple go评论83阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2012年10月12日 06:30:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/12849559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定