Properly pass arguments to Go Exec

不问归期 提交于 2019-12-07 13:15:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!