doudouchan5830 2019-07-17 15:12
浏览 2281
已采纳

在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.

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 汇川EASY521plc电子凸轮
  • ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
  • ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
  • ¥60 基于MATLAB的TAOD算法
  • ¥15 Groimp使用疑问
  • ¥15 MDK–ARM里一直找不到调试器
  • ¥15 oracle中sql查询问题
  • ¥15 vue使用gojs3.0版本,在nodeDataArray中的iconSrc使用gif本地路径,展示出来后动画是静态的,不是动态的
  • ¥100 代写个MATLAB代码,有偿
  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图