dongmei8209 2016-11-18 05:53
浏览 1038
已采纳

如何在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 2017-04-11 03:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)