2017-04-06 59 views
4

我希望我的方法能夠以exec作爲字符串接收命令。如果輸入字符串有空格,我如何將它分割爲cmd,args爲os.exec?如何使用空格字符串創建os.exec命令結構

的文件說,創建我Exec.Cmd結構像

cmd := exec.Command("tr", "a-z", "A-Z") 

這工作得很好:

a := string("ifconfig") 
cmd := exec.Command(a) 
output, err := cmd.CombinedOutput() 
fmt.Println(output) // prints ifconfig output 

這種失敗:

a := string("ifconfig -a") 
cmd := exec.Command(a) 
output, err := cmd.CombinedOutput() 
fmt.Println(output) // 'ifconfig -a' not found 

我試圖strings.Split(一),但收到錯誤消息:不能使用(類型[]字符串)作爲參數中的類型字符串給exec.Command

+0

您使用strings.Split()不正確golang.org/pkg/strings/#拆分你需要提供一個分隔符。 so .. strings.Split(a,「」)在一個空間上分割,其次,你不能分割一個切片,因爲它已經被分割,所以你的變量「a」已經是一個切片,而不是一個字符串。最後,你也可以定義你的切片而不是分割字符串。 a:= [] string {「inconfig」,「a」}。 – reticentroot

回答

5

請檢查: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput

您的代碼會失敗,因爲exec.Command需要命令參數與實際分開命令名稱

strings.Split簽名(https://golang.org/pkg/strings/#Split):

func Split(s, sep string) []string 

你想實現什麼:

command := strings.Split("ifconfig -a", " ") 
if len(command) < 2 { 
    // TODO: handle error 
} 
cmd := exec.Command(command[0], command[1:]...) 
stdoutStderr, err := cmd.CombinedOutput() 
if err != nil { 
    // TODO: handle error more gracefully 
    log.Fatal(err) 
} 
// do something with output 
fmt.Printf("%s\n", stdoutStderr) 
+0

'exec.Command(command ...)'更簡單IMO ;-) – kostix

+2

@kostix不,它不起作用。文檔說:'func Command(name string,arg ... string)* Cmd' - 因此你必須單獨傳遞第一個參數(命令名)。否則,你會產生錯誤:'沒有足夠的參數調用exec.Command'。我在@Mark的答案中指出了這一點,因爲他犯了同樣的錯誤。 – mwarzynski

+0

傻我 - 感謝您的糾正! ;-) – kostix

4
args := strings.Fields("ifconfig -a ") 
exec.Command(args[0], args[1:]...) 

strings.Fields()上的空白分裂,並返回一個切片

...擴展片分爲單獨的字符串參數

+1

執行你的代碼會產生一個錯誤:'調用exec.Command時沒有足夠的參數'。 您需要單獨傳遞命令名稱。 – mwarzynski

+0

謝謝@mwarzynski,更新。 – Mark

相關問題