为了账号安全,请及时绑定邮箱和手机立即绑定

使用 golang 运行命令行?

使用 golang 运行命令行?

ITMISS 2021-10-25 18:28:58
我只是在玩 golang。我很好奇如何从 go 运行 gulpfile 任务?从终端典型运行的 Gulp 任务:gulp serv.dev我怎么能从 golang 运行这行简单的代码:package mainimport (    "net/http"    "github.com/julienschmidt/httprouter"    "fmt")func main() {    //what do I put here to open terminal in background and run `gulp serv.dev`}
查看完整描述

3 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

更通用,更好的输出。


使用exec.Command以及缓冲区来记录输出并仅在有用时显示它。


您甚至可以通过使用可变参数,即任意数量元素的参数,使函数与任何命令一起工作。


适当地标记未处理的错误,因此如果命令失败,您将被告知是哪一个以及原因。


最后请注意,Go 虽然具有表现力,但它是一种非常原始的语言。它白白握着你的手。您将不得不自己编写大量程序。


示例代码:


package main


import (

    "bytes"

    "fmt"

    "os"

    "os/exec"

    "runtime"

    "strings"

)


func main() {

    runCommand(currentFunction(), "ping", "-c1", "google.commm")

}


func commandErrorMessage(stderr bytes.Buffer, program string) string {

    message := string(stderr.Bytes())


    if len(message) == 0 {

        message = "the command doesn't exist: " + program + "\n"

    }


    return message

}


func currentFunction() string {

    counter, _, _, success := runtime.Caller(1)


    if !success {

        println("functionName: runtime.Caller: failed")

        os.Exit(1)

    }


    return runtime.FuncForPC(counter).Name()

}


func printCommandError(stderr bytes.Buffer, callerFunc string, program string, args ...string) {

    printCommandErrorUbication(callerFunc, program, args...)

    fmt.Fprintf(os.Stderr, "%s", commandErrorMessage(stderr, program))

}


func printCommandErrorUbication(callerFunc string, program string, args ...string) {

    format := "error at: %s: %s %s\n"

    argsJoined := strings.Join(args, " ")

    fmt.Fprintf(os.Stderr, format, callerFunc, program, argsJoined)

}


func runCommand(callerFunc string, program string, args ...string) {

    command := exec.Command(program, args...)

    var stderr bytes.Buffer

    command.Stderr = &stderr

    fail := command.Run()


    if fail != nil {

        printCommandError(stderr, callerFunc, program, args...)

        os.Exit(1)

    }

}

示例运行:


$ go run test.go

error at: main.main: ping -c1 google.commm

ping: google.commm: Name or service not known

exit status 1


查看完整回答
反对 回复 2021-10-25
  • 3 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号