doudouchan5830
2019-07-17 15:12
浏览 1.4k

在Golang中使用exec.Command,如何打开新终端并执行命令?

I am able to get the following command to open a new terminal and execute the command when I directly input it inside a terminal, but I can not get it to work when I use the exec.Commmand function in go.

osascript -e 'tell application "Terminal" to do script "echo hello"'

I think the issue lies within the double and single quotes, but I am not exactly sure what is causing the error.

c := exec.Command("osascript", "-e", "'tell", "application", `"Terminal"`, "to", "do", "script", `"echo`, `hello"'`)
if err := c.Run(); err != nil {
     fmt.Println("Error: ", err)
}

As of now the code is returning Error: exit status 1, but I would like the code to open a terminal window and execute the command.

图片转代码服务由CSDN问答提供 功能建议

当我在A中直接输入终端时,我能够获得以下命令以打开新终端并执行该命令 终端,但当我在go中使用exec.Commmand函数时却无法正常工作。

  osascript -e'告诉应用程序“ Terminal”执行脚本“ echo hello  “'
   
 
 

我认为问题出在双引号和单引号之内,但我不确定是什么引起了错误。 \ n

  c:= exec.Command(“ osascript”,“ -e”,“'tell”,“ application”,`“ Terminal”`,“ to”,“ do”,“ script”,  '“ echo`,`hello”'`)
if err:= c.Run();  err!= nil {
 fmt.Println(“ Error:”,err)
} 
   
 
 

到目前为止,代码正在返回错误:退出状态1 ,但是我希望代码打开终端窗口并执行命令。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douya8978 2019-07-17 16:18
    已采纳

    After playing some time found this:

    cmd := exec.Command("osascript", "-s", "h", "-e",`tell application "Terminal" to do script "echo test"`)
    

    Apparently you should give the automator script in 1 argument and also use ticks (`) as the string literals for go.

    "-s", "h" is for automator program to tell you human readable errors.

    My complete test code is as follows:

    package main
    
    import (
        "fmt"
        "os/exec"
        "io/ioutil"
        "log"
        "os"
     )
    // this is a comment
    
    func main() {
        // osascript -e 'tell application "Terminal" to do script "echo hello"'
        cmd := exec.Command(`osascript`, "-s", "h", "-e",`tell application "Terminal" to do script "echo test"`)
        // cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
        stderr, err := cmd.StderrPipe()
        log.SetOutput(os.Stderr)
    
        if err != nil {
            log.Fatal(err)
        }
    
        if err := cmd.Start(); err != nil {
            log.Fatal(err)
        }
    
        slurp, _ := ioutil.ReadAll(stderr)
        fmt.Printf("%s
    ", slurp)
    
        if err := cmd.Wait(); err != nil {
            log.Fatal(err)
        }
    }
    
    

    PS: osascript is the command line interface for Automator app in macOS.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题