在 Go 中执行 shell 命令 [英] Exec a shell command in Go

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

问题描述

我希望在 Go 中执行一个 shell 命令,并在我的程序中以字符串的形式获取结果输出.我看到了 Rosetta Code 版本:

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()

但这并没有以我可以通过编程方式访问的方式捕获实际的标准输出或错误 - 那些仍然打印到常规标准输出/标准错误.我看到使用 Pipe 作为 out 或 err 可以在其他地方提供帮助,但没有示例说明如何这样做.有什么想法吗?

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?

推荐答案

这个答案不代表 Go 标准库的当前状态.请查看@Lourenco 的回答以获取最新方法!

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.

package main

import (
   "fmt"
   "exec"
   "os"
   "bytes"
   "io"
)

func main() {
    app := "/bin/ls"
    cmd, err := exec.Run(app, []string{app, "-l"}, nil, "", exec.DevNull, exec.Pipe, exec.Pipe)

    if (err != nil) {
       fmt.Fprintln(os.Stderr, err.String())
       return
    }

    var b bytes.Buffer
    io.Copy(&b, cmd.Stdout)
    fmt.Println(b.String())

    cmd.Close()
}

这篇关于在 Go 中执行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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