第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 golang 運(yùn)行命令行?

使用 golang 運(yùn)行命令行?

ITMISS 2021-10-25 18:28:58
我只是在玩 golang。我很好奇如何從 go 運(yùn)行 gulpfile 任務(wù)?從終端典型運(yùn)行的 Gulp 任務(wù):gulp serv.dev我怎么能從 golang 運(yùn)行這行簡單的代碼: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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個贊

更通用,更好的輸出。


使用exec.Command以及緩沖區(qū)來記錄輸出并僅在有用時(shí)顯示它。


您甚至可以通過使用可變參數(shù),即任意數(shù)量元素的參數(shù),使函數(shù)與任何命令一起工作。


適當(dāng)?shù)貥?biāo)記未處理的錯誤,因此如果命令失敗,您將被告知是哪一個以及原因。


最后請注意,Go 雖然具有表現(xiàn)力,但它是一種非常原始的語言。它白白握著你的手。您將不得不自己編寫大量程序。


示例代碼:


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)

    }

}

示例運(yùn)行:


$ go run test.go

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

ping: google.commm: Name or service not known

exit status 1


查看完整回答
反對 回復(fù) 2021-10-25
  • 3 回答
  • 0 關(guān)注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號