我有一個非常簡單的 Go 應用程序,名為myApp,它應該在 macOS 上啟動一個新的終端窗口:package mainimport ( "fmt" "os/exec")func main() { err := exec.Command("open", "-a", "Terminal", "/Users/ns/go/").Run() if err != nil { fmt.Println(err) }}但是,當我運行該應用程序時,我得到以下輸出:ns:~/go/src/github.com/nevadascout/myApp $ go install && myAppexit status 1open -a Terminal /Users/ns/go/如果我在終端中手動運行命令 ( ),它就會起作用。我缺少什么?
1 回答

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
來自文檔:
與 C 和其他語言的“系統”庫調用不同,os/exec 包有意不調用系統 shell,也不擴展任何 glob 模式或處理通常由 shell 完成的其他擴展、管道或重定向。該包的行為更像是 C 的“exec”函數系列。要擴展 glob 模式,請直接調用 shell,注意轉義任何危險輸入,或使用 path/filepath 包的 Glob 函數。要擴展環境變量,請使用 os 包的 ExpandEnv。
因此,您需要運行bash -c
命令并將上述命令作為參數傳遞。像這樣的東西:
exec.Command("bash",?"-c",?"open",?"-a",?"Terminal",?"~/go/").Run()
對于 Windows,您應該使用cmd /C
.?例子:
exec.Command("cmd",?"/C",?...)
- 1 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消