donatJ
donatJ

Reputation: 3374

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.

Upvotes: 3

Views: 5763

Answers (3)

Squeeseio
Squeeseio

Reputation: 96

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.

Upvotes: 8

user811773
user811773

Reputation:

Try

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

or try

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

To print the error (if any) and the combined output:

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

Upvotes: 0

amattn
amattn

Reputation: 10065

Your are probably just missing quotes. Try:

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

Also, instead of println, idiomatic go usually looks like:

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

Upvotes: 1

Related Questions