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