在Go中实时输出来自exec命令的stdout

编程入门 行业动态 更新时间:2024-10-21 05:47:52
本文介绍了在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

本文发布于:2023-11-02 14:37:40,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实时   命令   exec   stdout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!