在Go中实时输出来自exec命令的stdout [英] Print the stdout from exec command in real time in Go

查看:1082
本文介绍了在Go中实时输出来自exec命令的stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的Go工具,它基本上允许用户定义一个命令,而不是使用 os / exec 运行。



我的问题是我想向用户显示命令的输出(stdout / stderr)。



一个例子可能如下所示:
用户最后定义了一个命令 sh test.sh
test.sh 的内容:

  echo开始
睡眠7s
echo完成

在我目前的实现中,用户只能看到一次输出完成的命令完成。在上面的例子中,直到 sleep 命令和第二个 echo 命令才会看到输出 Start c $ c> finish。



我现在检索如下命令的输出:

  cmd:= exec.Command(command,args ...)
cmd.Dir = dir
//附加到标准读出命令可能打印的内容
stdout,err:= cmd.StdoutPipe()
如果err!= nil {
log.Panic(err)
}
//执行命令
if err:= cmd.Start(); err!= nil {
log.Panic(err)
}

buf:= new(bytes.Buffer)
buf.ReadFrom(stdout)
log.Print(buf.String())

是否有可能读取stdout / stderr在实时中。这意味着只要用户定义的命令创建并输出它就会打印出来吗?

解决方案

谢谢mh-cbon。这促使我朝着正确的方向前进。



现在代码看起来像这样,并且完全符合我的要求。我还发现,当我使用 Run()而不是 Start()时,程序的执行只会在

  cmd:= exec.Command(command,args ...)
cmd.Dir = dir

var stdBuffer bytes.Buffer
mw:= io.MultiWriter(os.Stdout,& stdBuffer)

cmd.Stdout = mw
cmd.Stderr = mw

//执行命令
if err:= cmd.Run(); err!= nil {
log.Panic(err)
}

log.Println(stdBuffer.String())


I have a small Go tool which basically allows the user to define an command that than will be run using os/exec.

My problem is that I want to show the user the output (stdout/stderr) of the command.

An example could look like this: The user defines a command that in the end is sh test.sh. Content of test.sh:

echo "Start"
sleep 7s
echo "Done"

With my current implementation the user can only see the output once the complete command finished. In the example above the user wouldn't see the output Start until the sleep command and the second echo finish.

I currently retrieve the output of the command like this:

cmd := exec.Command(command, args...)
cmd.Dir = dir
// Attach to the standard out to read what the command might print
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Panic(err)
}
// Execute the command
if err := cmd.Start(); err != nil {
    log.Panic(err)
}

buf := new(bytes.Buffer)
buf.ReadFrom(stdout)
log.Print(buf.String())

Is it somehow possible to read the stdout/stderr in real-time. Meaning that as soon as the user defined command creates and output it is printed?

解决方案

Thank you mh-cbon. That pushed me in the right direction.

The code now looks like this and does exactly what I want it to do. I also found that when I use Run() instead of Start() the execution of the program only continues after the command has finished.

cmd := exec.Command(command, args...)
cmd.Dir = dir

var stdBuffer bytes.Buffer
mw := io.MultiWriter(os.Stdout, &stdBuffer)

cmd.Stdout = mw
cmd.Stderr = mw

// Execute the command
if err := cmd.Run(); err != nil {
    log.Panic(err)
}

log.Println(stdBuffer.String())

这篇关于在Go中实时输出来自exec命令的stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆