dpoh61610 2019-04-17 20:18 采纳率: 100%
浏览 120

如何解决“语法错误:在Go脚本中运行`exec.Command`时出现未知令牌无法进入此处”的问题

I am trying to run this Apple Script command with osascript in my Go script and I'm getting the error 0:1: syntax error: A unknown token can’t go here. (-2740).

This is the command that, when run in Terminal, works great!

/usr/bin/osascript -e 'on run {f, c}' -e 'tell app "Finder" to set comment of (POSIX file f as alias) to c' -e end "/Users/computerman/Desktop/testfile.png" "Hello, World"

My Go script below actually outputs the above string, and I can literally cut and paste it in Terminal and it works. However, running the Go script itself I get the aforementioned error.

Please help!

This is on MacOS 10.14.4 (18E2034). I tried replacing the fmt.Sprintf with simpler string with \"Finder"\ and have the same exact issue.


import (
    "fmt"
    "log"
    "os"
    "os/exec"
)

func main() {
    filepath := "/Users/computerman/Desktop/testfile.png"
    comment := "Hello, World"
    onrun := "'on run {f, c}'"
    command := fmt.Sprintf(`'tell app "Finder" to set comment of (POSIX file f as alias) to c' -e end "%s" "%s"`, filepath, comment)
    log.Println("/usr/bin/osascript", "-e", onrun, "-e", command)
    cmd := exec.Command("/usr/bin/osascript", "-e", onrun, "-e", command)
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin

    err := cmd.Run()
    if err != nil {
        log.Println(err)
    }
}

When I do go run main.go I get this in Terminal

2019/04/17 13:02:28 exit status 1

I expect the output of

Hello, World

And no errors. Plus, the comment field in the file to be updated with Hello, World.

  • 写回答

2条回答 默认 最新

  • dth54864 2019-04-17 20:25
    关注

    You need to break out the -e on the end of command too and the comment, something like this. This makes the same number of parameters as in the original command hopefully.

    func main() {
        filepath := "/Users/computerman/Desktop/testfile.png"
        comment := "Hello, World"
        onrun := "'on run {f, c}'"
        command := fmt.Sprintf(`'tell app "Finder" to set comment of (POSIX file f as alias) to c'`)
        end := fmt.Sprintf(`end "%s")`, filepath)
        log.Println("/usr/bin/osascript", "-e", onrun, "-e", command, "-e", end, comment)
        cmd := exec.Command("/usr/bin/osascript", "-e", onrun, "-e", command, "-e", end, comment)
        cmd.Stderr = os.Stderr
        cmd.Stdout = os.Stdout
        cmd.Stdin = os.Stdin
    
        err := cmd.Run()
        if err != nil {
            log.Println(err)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置