【问题标题】:Properly pass arguments to Go Exec正确地将参数传递给 Go Exec
【发布时间】:2011-10-21 04:57:36
【问题描述】:

我正在尝试学习 Go,作为开始,我想尝试构建一个超级简单的 Web 服务器来控制我的 iTunes。我过去曾多次使用osascript -e 'Tell Application "iTunes" to playpause' 来实现此目的,并认为我可以在此处简单地取消对 osascript 的调用。

注释掉的“say 5”命令确实工作。

package main

import "exec"
//import "os"

func main() {

    var command = "Tell Application 'iTunes' to playpause"
    //var command = "say 5"

    c := exec.Command("/usr/bin/osascript", "-e", command)
//  c.Stdin = os.Stdin
    _, err := c.CombinedOutput()
    println(err.String());


}

我收到的回复如下 -

jessed@JesseDonat-MBP ~/Desktop/goproj » ./8.out
exit status 1
[55/1536]0x1087f000

我不确定从这里往哪里走,任何方向都将不胜感激。

【问题讨论】:

  • 请将osascript输出的文字记录到stderr。有问题的可能是您的 AppleScript 代码,而不是您的 Go。

标签: macos osx-snow-leopard exec go


【解决方案1】:

我得到了它的工作

package main

import (
    "fmt"
    "exec"
)

func main() {
    command := "Tell Application \"iTunes\" to playpause"

    c := exec.Command("/usr/bin/osascript", "-e", command)
    if err := c.Run(); err != nil {
        fmt.Println(err.String())
    }
}

如果参数中有空格,我认为 exec.Command(...) 会在参数中添加双引号,因此您只需在需要它们的地方转义 \"。

【讨论】:

  • 仅当您在命令 shell 中键入内容时才需要转义引号。 Go 是显式启动一个程序并将每个参数作为单独的值传递。每个参数(参数)都是它自己在参数数组中的条目。单个参数可以包含空格或引号而没有任何转义。
【解决方案2】:

您可能只是缺少引号。试试:

var command = "\"Tell Application 'iTunes' to playpause\""

另外,惯用的 go 不是 println,通常看起来像:

if err != nil {
    fmt.Println(err.String());
}

【讨论】:

  • 好吧,我试过了,得到了一个新的 - 恐慌:运行时错误:无效的内存地址或零指针取消引用 [信号 0xa 代码=0x2 地址=0x14 pc=0x20a8] runtime.panic+0x92 /Users /jessed/go/src/pkg/runtime/proc.c:1254 runtime.panic(0x33788, 0x1048a3d8)
  • 你和err聊天了吗?如果 err 为 nil,你会在 println 的行上出现恐慌
【解决方案3】:

试试

c := exec.Command("/usr/bin/osascript", "-e", "say 5")
output, err := c.CombinedOutput()

或者试试

c := exec.Command("/usr/bin/osascript", "-e", "say 5")
c.Stdin = os.Stdin
output, err := c.CombinedOutput()

打印错误(如果有)和组合输出:

if err != nil { fmt.Println(err) }
fmt.Print(string(output))

【讨论】:

  • 感谢您的回复,但恐怕它仍然无法正常工作并返回退出状态1 [55/1536]0x1088e000
  • 我更新了我的答案。如果它不起作用,我不知道如何解决问题。
  • 您的回答 确实 工作 - 但现在我试图通过“告诉应用程序 'iTunes' 播放暂停”并再次返回 exit status 1 - 我已经更新我的旧帖子中包含我目前正在使用的代码示例。任何帮助将不胜感激。
猜你喜欢
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2014-04-02
相关资源
最近更新 更多