macos - 尝试从 Go 应用启动终端时出现 "exit status 1"

标签 macos go terminal

<分区>

我有一个名为 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", ...)

关于macos - 尝试从 Go 应用启动终端时出现 "exit status 1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57026265/

相关文章:

macos - 寻找一个终端命令来解析 MacOSX 字典数据文件

macos - 当我打开 zsh 时,一些奇怪的字符显示为我的提示符(OSX 上的 oh-my-zsh)

macos - 如何在 bash 函数中使用 pbcopy?可以脚本化吗?

go - Go 中的方法前缀

testing - 如何在 golang 基准测试中正确启动时间和停止时间?

shell - android通过命令行启用禁用蓝牙

swift - NSWindow 位置

ios - XCode 失去了语法高亮的能力

macos - 去安装: directory outside of GOPATH

xcode - 我如何在 Mac 上运行 asm 文件?