cobra-cli 将所有参数和标志传递给可执行文件

我有一个 cobra CLI 用于我自己的东西。现在我想添加常用的可执行文件,例如 kubectl,calicoctl作为将使用所有参数和标志的子命令


mywrapper kubectl get all --all-namespaces

mywrapper kubectl create deployment nginx --image=nginx --port=80

重现眼镜蛇项目


mkdir mywrapper; cd mywrapper; go mod init mywrapper; cobra-cli init .

并添加一个子命令,例如 kubectl


cobra-cli add kubectl 

./cmd/kubectl.go然后填充


package cmd


import (

    "fmt"

    "os/exec"

    "strings"


    "github.com/spf13/cobra"

)


var kubectlCmd = &cobra.Command{

    Use:   "kubectl",

    Short: "run kubectl",

    Run: func(cmd *cobra.Command, args []string) {

        out, err := exec.Command("/bin/bash", "-c", fmt.Sprintf("kubectl %v", strings.Join(args, " "))).Output()

        if err != nil {

            fmt.Println(err)

        }

        fmt.Println(string(out))

    },

}


func init() {

    rootCmd.AddCommand(kubectlCmd)

}

我现在可以运行kubectl命令,例如 go run . kubectl get pods。但是当添加标志时它会失败,例如 go run . kubectl get pods --selector app=nginx


慕森王
浏览 65回答 1
1回答

一只斗牛犬

在 .之后传递你的标志--。双破折号 (--) 用于表示命令选项的结尾。在我们的例子中,需要区分传递给的标志go和没有传递的标志。双破折号后的所有内容都不会被视为go的标志。我尝试使用 gcloud:package cmdimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os/exec"&nbsp; &nbsp; "github.com/spf13/cobra")var gcloudCmd = &cobra.Command{&nbsp; &nbsp; Use:&nbsp; &nbsp;"gcloud",&nbsp; &nbsp; Short: "run gcloud",&nbsp; &nbsp; Run: func(cmd *cobra.Command, args []string) {&nbsp; &nbsp; &nbsp; &nbsp; out, err := exec.Command("gcloud", args...).Output()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(string(out))&nbsp; &nbsp; },}func init() {&nbsp; &nbsp; rootCmd.AddCommand(gcloudCmd)}然后尝试:$ go run . gcloud compute regions list -- --filter="id<1250"NAME&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CPUS&nbsp; DISKS_GB&nbsp; ADDRESSES&nbsp; RESERVED_ADDRESSES&nbsp; STATUS&nbsp; TURNDOWN_DATEasia-east1&nbsp; &nbsp; 0/24&nbsp; 0/4096&nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UPeurope-west1&nbsp; 0/24&nbsp; 0/4096&nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UPus-central1&nbsp; &nbsp;0/24&nbsp; 0/4096&nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UPus-east1&nbsp; &nbsp; &nbsp; 0/24&nbsp; 0/4096&nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UPus-west1&nbsp; &nbsp; &nbsp; 0/24&nbsp; 0/4096&nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; 0/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UP添加更多标志:$ go run . gcloud compute regions list -- --filter="id<1250" --format="table(name,id)"NAME&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IDasia-east1&nbsp; &nbsp; 1220europe-west1&nbsp; 1100us-central1&nbsp; &nbsp;1000us-east1&nbsp; &nbsp; &nbsp; 1230us-west1&nbsp; &nbsp; &nbsp; 1210
打开App,查看更多内容
随时随地看视频慕课网APP