11

I want to execute Binary Files inside GoLang Program.

Here is my code:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    output, _ := exec.Command("/home/user/Golang/bin/hello").Output()
    fmt.Println(output)
}

But I get the output as: []

Thanks in advance.

0

2 Answers 2

13

I can get the output.

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    output, err := exec.Command("/Users/duguying/gopath/bin/test").Output()
    if err!=nil {
        fmt.Println(err.Error())
    }
    fmt.Println(string(output))
}

check you binary file first or binary filepath is correcting. try to print out your error message.

Sign up to request clarification or add additional context in comments.

Comments

1

When I'm looking at the source of the exec.Command() it doesnt return an error but only returns Cmd which is struct in the package exe : source

....

func Command(name string, arg ...string) *Cmd {
    cmd := &Cmd{
        Path: name,
        Args: append([]string{name}, arg...),
    }
    if filepath.Base(name) == name {
        if lp, err := LookPath(name); err != nil {
            cmd.lookPathErr = err
        } else {
            cmd.Path = lp
        }
    }
    return cmd
}

....

I have succesfully got the binary file running using this code :

package main

import (

    "fmt"
    "os/exec"
)

func main() {
    command:= exec.Command("Your binary file path")

    // set var to get the output
    var out bytes.Buffer

     // set the output to our variable
     command.Stdout = &out
     err = command.Run()
     if err != nil {
         log.Println(err)
     }

    fmt.Println(out.String())
}

This one works for me for running a binary file that will print some random string.

3 Comments

Is there a better way to this? This would run as a separate job. Running it under goroutines makes it even bad. More jobs running at the same time, which will eventually use all server resources.
For me, on Windows, exec only works with full path to executable. E.g. ./test.bat doesn't work.
I propose pull request on this line err = command.Run() to be like this err := command.Run() to prevent undeclared name: err

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.