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

如何在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.

图片转代码服务由CSDN问答提供 功能建议

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

这是我的 代码:

 包main 
 
import(
“ fmt” 
“ os / exec” 
)
 
func main(){
输出,  _:= exec.Command(“ / home / user / Golang / bin / hello”)。Output()
 fmt.Println(output)
} 
   
 
 <  p>但是我得到的输出为:[]  
 
 

谢谢。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    打赏 评论
  • dongqiu3709 2016-11-18 06:25

    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.

    打赏 评论

相关推荐 更多相似问题