简体   繁体   English

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

[英]How to run Binary Files inside GoLang Program?

I want to execute Binary Files inside GoLang Program. 我想在GoLang程序中执行二进制文件。

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. 提前致谢。

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. 尝试打印出您的错误消息。

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 当我在看的源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
}

....

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. 这个适用于我运行二进制文件,将打印一些随机字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM