Search code examples
macososx-snow-leopardexecgo

Properly pass arguments to Go Exec


I'm trying to learn go and as a start I wanted to try to throw together a super simple web server for controlling my iTunes. I've used osascript -e 'Tell Application "iTunes" to playpause' to this purpose many times in the past and thought I could simply sluff the call off to osascript here.

The commented out "say 5" command does work.

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());


}

The response I am receiving from this is as follows -

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

I'm not exactly sure where to go from here and any direction would be greatly appreciated.


Solution

  • I got it working with this

    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())
        }
    }
    

    I think exec.Command(...) adds double quotes to the parameters if there is spaces in them, so you only need to escape \" where you need them.