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

Tes*_*min 3 go

我想在GoLang程序中执行二进制文件.

这是我的代码:

package main

import (
    "fmt"
    "os/exec"
)

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

但我得到的输出为:[]

提前致谢.

小智 7

我可以得到输出.

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))
}
Run Code Online (Sandbox Code Playgroud)

首先检查二进制文件或二进制文件路径是否正在纠正.尝试打印出您的错误消息.


Guj*_*ana 1

当我查看源代码时,exec.Command()它不会返回错误,而只返回Cmd包中的结构exe

....

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
}

....
Run Code Online (Sandbox Code Playgroud)

我已经使用以下代码成功运行了二进制文件:

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())
}
Run Code Online (Sandbox Code Playgroud)

这个适用于我运行一个将打印一些随机字符串的二进制文件。