2016-11-18 606 views
1

我想在GoLang程序中執行二進制文件。如何在GoLang程序中運行二進制文件?

這裏是我的代碼:

package main 

import (
    "fmt" 
    "os/exec" 
) 

func main() { 
    output, _ := exec.Command("/home/user/Golang/bin/hello").Output() 
    fmt.Println(output) 
} 

但我得到的輸出:提前[]

感謝。

+0

檢查'Output'返回的錯誤。另外,使用'fmt.Printf(「%s \ n」,output)'將輸出視爲文本。 –

回答

1

當我在看exec.Command()源它不返回一個錯誤,但只返回Cmd這是結構在包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 
} 

.... 

此代碼:

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()) 
} 

這個爲我運行二進制文件打印一些隨機字符串。

+0

有沒有更好的辦法呢?這將作爲一個單獨的工作來運行。在goroutine下運行它使它變得更糟糕。同時運行更多作業,最終將使用所有服務器資源。 – Mir

5

我可以得到輸出。

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)) 
} 

檢查你的二進制文件首先或二進制文件路徑正在糾正。嘗試打印出您的錯誤信息。

相關問題