登录
首页 >  Golang >  Go问答

如何在golang中使用exec.Command打开新终端并运行命令?

来源:stackoverflow

时间:2024-03-14 19:54:28 246浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何在golang中使用exec.Command打开新终端并运行命令?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

当我直接在终端中输入以下命令时,我能够打开一个新终端并执行该命令,但当我在 go 中使用 exec.commmand 函数时,我无法让它工作。 p>

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

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

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

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


解决方案


玩了一段时间后发现:

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

显然,您应该在 1 个参数中给出自动程序脚本,并使用刻度 (`) 作为 go 的字符串文字。

"-s", "h" 用于自动化程序告诉您人类可读的错误。

我的完整测试代码如下:

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\n", slurp)

    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }
}

ps:osascript 是 macos 中 automator 应用程序的命令行界面。

今天关于《如何在golang中使用exec.Command打开新终端并运行命令?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>