1. 程式人生 > >Run System Commands & Binary Files · GolangCode

Run System Commands & Binary Files · GolangCode

Within Go, like other languages, we have the ability to call external binaries. These allow us to do all sorts of things, but in our example we’re just going to print out our go version by calling our copy (located in /usr/local/go/bin on my computer).

The Command function within the os/exec

package will allow us to do this. It accepts at least one string - the name of the command/binary you’re trying to run - followed by any number of strings for it’s parameters.

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {

    // Print Go Version
    cmdOutput, err := exec.Command("go", "version").Output()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", cmdOutput)
}