我有一个名为 myApp
的非常简单的 Go 应用程序,它应该在 macOS 上启动一个新的终端窗口:
package main
import (
"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 && myApp
exit status 1
如果我在终端中手动运行命令 (open -a Terminal/Users/ns/go/
),它会起作用。
我错过了什么?
来自docs :
Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.
因此您需要运行 bash -c
命令并将上述命令作为参数传递。像这样:
exec.Command("bash", "-c", "open", "-a", "Terminal", "~/go/").Run()
对于 Windows,您应该使用 cmd/C
。示例:
exec.Command("cmd", "/C", ...)