dongmei8209
dongmei8209
2016-11-18 05:53

如何在GoLang程序中运行二进制文件?

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douzhuo6931 douzhuo6931 4年前

    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.

    点赞 评论 复制链接分享
  • dongqiu3709 dongqiu3709 5年前

    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.

    点赞 评论 复制链接分享