Wednesday, May 20, 2015

GO Programming Language : Executing external system command using "Go" language

Prerequisite : you must have basic knowledge of how to execute a programming in Go language.
How execute first hello world program.

In following section, we will discuss, how to execute an external program. My goal is, instead of executing a command in terminal, I want to execute using Go programming language.

Source Code:
package main
import (
        "bytes"
        "fmt"
        "log"
        "os/exec"
        "strings"
)

func main() {
        cmd := exec.Command("docker","ps","-a")
        cmd.Stdin = strings.NewReader("")
        var out bytes.Buffer
        cmd.Stdout = &out
        err := cmd.Run()
        if err != nil {
                log.Fatal(err)
        }
        fmt.Printf("Output \n",out.String())
}

Output:
Ahh... I got a long list of output as expected.


Description:
In the source, I was trying to execute the following command
docker ps -a
For this, I pass the above command as argument to function "command" as different strings.
When I tried to pass whole command (i.e. docker ps -a) as a single string, it produce an error saying "exec: "docker ps -a": executable file not found in $PATH exit status 1". This means the first argument is the name of the executable file and in order to execute the command it tries to search the file mentioned in first string in function "exec.Command()". Since in my case the actual executable file name is "docker", this couldn't execute the "docker ps -a" command.
So, every word in the command (or the external program we want to execute) must be provided as different string to "exec.Command()".

That's all for now.


-Enjoy


 

No comments:

Post a Comment