在Go语言中,当使用exec执行命令时,如何获取命令在运行时的输出呢?

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

How would you get the output of a command as it's running when exec-ing in Go?

问题

到目前为止,我看到了几种不同的方法,可以在Go语言中轻松执行shell命令并获取其输出。
然而,有很多命令在程序运行时会输出内容,例如git clone ...

如果使用类似以下方式执行git clone http://some.repo.git

out, err := exec.Command("...").Output()

显然,没有任何输出。至少在我的经验中是这样的。是否有一种简单的方法或模式可以实现显示正在运行的命令的实时输出?

英文:

So far I've seen a few different ways whereby you can easily execute a shell command in go and yield it's output.
However, there are a ton of commands that output while the program is still running, for example, git clone ...

If git clone http://some.repo.git is executed using something like:

out, err := exec.Command("...").Output()

There doesn't seem to be any output as it's running obviously. Or at least in my experiance that seems to be the case. Is there a simple way or pattern that can be implemented to show the live output of the command that is being ran?

答案1

得分: 5

你可以通过将管道连接到命令的stdout来获取输出:

cmd := exec.Command("...")

pipe, err := cmd.StdoutPipe()

然后启动命令:

err := cmd.Start()

并读取其输出(定期地):

b := make([]byte, 1024, 1024)

n, err := pipe.Read(b)

// b 包含最多 1024 个字符的命令输出

最后,在管道被清空(没有输出留在管道中)后,调用Wait等待命令退出:

err := cmd.Wait()
英文:

You can get a pipe connected to the command's stdout:

cmd := exec.Command("...")

pipe, err := cmd.StdoutPipe()

Then start the command:

err := cmd.Start()

and read its output (periodically ever so often):

b := make([]byte, 1024, 1024)

n, err := pipe.Read(b)

// b contains up to 1024 characters of cmd's output

in the end, and with a drained pipe (no output left in the pipe), call Wait to wait for the command to exit:

err := cmd.Wait()

huangapple
  • 本文由 发表于 2014年6月18日 18:04:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/24282709.html
匿名

发表评论

匿名网友

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

确定