Exec a shell command in Go

前端 未结 7 1610
甜味超标
甜味超标 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:58

    None of the provided answers allow to separate stdout and stderr 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 the os/exec package. Look here: https://golang.org/pkg/os/exec/#Cmd

    Especially the members Stdin and Stdout,Stderr where any io.Reader can be used to feed stdin of your newly created process and any io.Writer can be used to consume stdout and stderr 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:

    package main
    
    import (
        "bytes"
        "fmt"
        "log"
        "os/exec"
    )
    
    const ShellToUse = "bash"
    
    func Shellout(command string) (error, string, string) {
        var stdout bytes.Buffer
        var stderr bytes.Buffer
        cmd := exec.Command(ShellToUse, "-c", command)
        cmd.Stdout = &stdout
        cmd.Stderr = &stderr
        err := cmd.Run()
        return err, stdout.String(), stderr.String()
    }
    
    func main() {
        err, out, errout := Shellout("ls -ltr")
        if err != nil {
            log.Printf("error: %v\n", err)
        }
        fmt.Println("--- stdout ---")
        fmt.Println(out)
        fmt.Println("--- stderr ---")
        fmt.Println(errout)
    }
    
    0 讨论(0)
提交回复
热议问题