Exec a shell command in Go

前端 未结 7 1608
甜味超标
甜味超标 2020-12-04 10:01

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 \"f         


        
7条回答
  •  离开以前
    2020-12-04 10:46

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

提交回复
热议问题