且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Go中执行shell命令

更新时间:2023-11-30 10:44:22

这个答案并不代表Go标准库的当前状态。请查看@ Lourenco的答案,了解最新的方法!

您的示例并不实际从stdout读取数据。这对我有效。

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