go - 如何在go中执行带有反斜杠的命令
问题描述
我想使用 go 返回应用程序版本的输出
为什么以下失败?
emulatorCmd := exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/Bot\`, `Framework\`, `Emulator.app`)
emulatorVersion, err := emulatorCmd.Output()
if err != nil {
log.Fatalf("cmd.Run() failed in emulator", err)
fmt.Println("Looks like you don't have the Bot Emulator installed yet, download here: https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v4.5.2")
} else {
fmt.Println("Emulator:", string(emulatorVersion))
}
给予:
cmd.Run() failed in emulator%!(EXTRA *exec.ExitError=exit status 1)
但是当我用名称中没有空格的应用程序替换命令时(因此,不需要反斜杠),例如
exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/FaceTime.app`)
它是成功的,给出:
Emulator: kMDItemVersion = "5.0"
我尝试将它们全部放在一个字符串中,但是命令中的空格需要用逗号分隔。还尝试使用两个“\”反斜杠,现在即使使用反引号也不起作用。
还查看了 go string literals 页面,但没有找到与此问题相关的内容: https ://golang.org/ref/spec#raw_string_lit
解决方案
您在命令行中需要的反斜杠用于转义空格,以防止它们被shell视为参数分隔符。由于在 Go 中没有涉及以这种方式执行的 shell,因此您不需要它们。你可以:
exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/Bot Framework Emulator.app`)
推荐阅读
- python - 使用python计算一维数组和nD数组之间的距离
- javascript - APIRTC 离开对话不允许重新进入
- java - 无法更改snackBar 中的变量值
- ios - 如何使用 SwiftUI 使 MKScaleView 在初始地图加载时正确显示
- bash - 递归查找和复制特定的 mimetype 文件
- python - 在请求中使用局部变量
- python - Python:在深度嵌套列表中搜索值
- javascript - VSCode 在导入自动完成时添加 .js 扩展名
- typescript - 在 Typescript 中定义静态可索引对象属性
- javascript - 我如何使用节点“文件名”命令