英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论