问题
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.
回答1:
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.
回答2:
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());
}
回答3:
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))
来源:https://stackoverflow.com/questions/7845130/properly-pass-arguments-to-go-exec