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 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决