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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵