在GO中执行外壳命令
我希望在GO中执行Shell命令,并将结果输出作为程序中的字符串获取。 看到 rosetta code 版本
package main
import "fmt"
import "exec"
func main() {
cmd, err := exec.Run("/bin/ls", []string{"/bin/ls"}, []string{}, "", exec.DevNull, exec.PassThrough, exec.PassThrough)
if (err != nil) {
fmt.Println(err)
return
}
cmd.Close()
我 我可以从编程上访问的方式 - 这些仍然打印到常规的Stdout / stderr。我看到使用管道作为外出或ERR可以在其他地方有所帮助,但没有这样做的例子。有什么想法吗?
I'm looking to execute a shell command in Go and get the resulting output as a string in my program. I saw the Rosetta Code version:
package main
import "fmt"
import "exec"
func main() {
cmd, err := exec.Run("/bin/ls", []string{"/bin/ls"}, []string{}, "", exec.DevNull, exec.PassThrough, exec.PassThrough)
if (err != nil) {
fmt.Println(err)
return
}
cmd.Close()
But this doesn't capture the actual standard out or err in a way that I can programatically access - those still print out to the regular stdout / stderr. I saw that using Pipe as the out or err could help elsewhere, but no example of how to do so. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
软件包“ exec”为更改了 有点一点。以下代码对我有用。
The package "exec" was changed a little bit. The following code worked for me.
提供的答案都没有允许分开
stdout
和stderr
,因此我尝试了另一个答案。首先,如果您查看
exec.cmd
在os/exec/exec
软件包中键入exec.cmd
的文档。在这里查看: https://golang.org/pkg/pkg/os/exec/exec/exec/qun.cmd尤其是成员
stdin
和stdout
,stderr
,其中任何io.reader
可用于喂食您新创建的过程的stdin
可以使用任何io.writer
用于消费命令的stdout
stder> stderr 。函数
shellOut
在以下程序中将运行您的命令,并将其输出和错误输出分别为字符串。由于参数值被执行为shell命令,请进行消毒
参数构建中使用的所有外部输入
价值。
可能不会在生产中以这种形式使用它。
None of the provided answers allow to separate
stdout
andstderr
so I try another answer.First you get all the info you need, if you look at the documentation of the
exec.Cmd
type in theos/exec
package. Look here: https://golang.org/pkg/os/exec/#CmdEspecially the members
Stdin
andStdout
,Stderr
where anyio.Reader
can be used to feedstdin
of your newly created process and anyio.Writer
can be used to consumestdout
andstderr
of your command.The function
Shellout
in the following programm will run your command and hand you its output and error output separatly as strings.As the parameter value is executed as a shell command, sanitize
all external inputs used in the construction of the parameter
value.
Probably don't use it in this form in production.
此答案不代表GO标准库的当前状态。请看一下@lourenco的答案对于最新的方法!
您的示例实际上没有读取您的示例来自Stdout的数据。这对我有用。
This answer does not represent the current state of the Go standard library. Please take a look at @Lourenco's answer for an up-to-date method!
Your example does not actually read the data from stdout. This works for me.
您可以尝试一下。
you may try this .
使用exec. -command函数用 /c flag和dir命令创建一个新的CMD进程作为参数
使用()方法捕获输出并打印。
Use the exec.Command function to create a new cmd process with the /C flag and the dir command as its argument
Capture output with output() method and print it.
这是一个简单的功能,它将运行您的命令并捕获错误,Stdout和stderr供您检查。您可以轻松地看到任何可能出错或报告给您的东西。
您可以这样使用(转换媒体文件):
我已经将其与GO 1.2-1.7一起使用
Here is a simple function that will run your command and capture the error, stdout, and stderr for you to inspect. You can easily see anything that might go wrong or be reported back to you.
You can use it like this (Converting a media file):
I've used this with Go 1.2-1.7
如果要在执行进度的情况下运行长期运行的脚本异步,则可以使用
io.multiwriter
捕获命令输出,然后将其转发到stdout/stderr
:If you want run long-running script asynchronously with execution progress, you may capture command output using
io.MultiWriter
and forward it tostdout/stderr
:去测试
go test
我没有在窗户上有Rosetta示例来工作。最后,我设法通过此命令超过了子过程的旧格式,以在Windows的Notepad中启动Outfile。一本手册中提到的等待常量参数不存在,因此我只是拒绝等待,因为用户将通过他们自己关闭程序或将其打开以重复使用。
您将更改OS.STDOUT ..将其更改为OS.Pipe作为先前的答案
编辑:我最终从Godoc OS等待了,等待已更改为方法,我成功地做到了:
然后我决定最终放置
。
I did not get the Rosetta example to work in my Windows Go. Finally I managed to go past the old format of the Subprocess with this command to start outfile in notepad in windows. The wait constant parameter mentioned in one manual did not exist so I just left out Wait as the user will close the program by themself or leave it open to reuse.
You would change the os.Stdout.. to os.Pipe as previous answer
EDIT: I got it finally from godoc os Wait, that Wait has changed to method of and I succeeded to do:
Then I decided finally to put
instead.
我最终这样做是为了获得退出错误代码,命令输出和错误:
在上面答案的帮助下(以及stackoverflow上的其他问题),希望这对某人有所帮助。
I ended up doing this to get exit error code, command output and error:
with the help from answers above (and other questions on stackoverflow), hope this helps someone.
Here's a great alternative using the cmdx library that makes executing commands and capturing output simpler and more intuitive:
Explanation
有关更多信息,请查看 github存储库。
Here's a great alternative using the cmdx library that makes executing commands and capturing output simpler and more intuitive:
Explanation
cmdx.RunCommandReturnOutput(command, args...)
: This function runs the specified command with the given arguments and returns the output as a string.For more information, check out the GitHub repository.