亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何在 Go 中使用 Cli 訪問一系列命令?

如何在 Go 中使用 Cli 訪問一系列命令?

Go
慕蓋茨4494581 2021-11-29 16:57:10
目前使用Codegangsta 的 Cli 庫。我運行這樣的命令:myGoProgram arg1 arg2 arg3 --flag1 flag1arg 跑步app.Action = func(c *cli.Context) {        fmt.Println("Context: ", c.Args())}返回:[arg1 arg2 arg3 --flag1 flag1arg](c.Args() 的返回類型)我如何訪問arg1, arg2, and arg3,但不能訪問--flag1or flag1arg?我必須遍歷這個數組嗎?
查看完整描述

2 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

好的,所以我所做的是創建兩個相同內容的數組,并相應地刪除元素以創建一個僅包含原始命令的數組。


func noFlagCliArgs(cliArgs []string) []string {

    a := cliArgs

    for pos, arg := range cliArgs {

        if strings.Compare(string(arg[0]), "-") == 0 {

            // Cut out two to get rid of flag and its argument

            a = append(a[:pos], a[pos+2:]...)

        }

    }

    return a

}


查看完整回答
反對 回復 2021-11-29
?
森林海

TA貢獻2011條經驗 獲得超2個贊

我認為您可能沒有正確定義標志,請參閱我編寫的這個示例:


package main


import (

    "fmt"

    "os"


    "github.com/codegangsta/cli"

)


func main() {

    app := cli.NewApp()

    app.Name = "so-example"

    app.Usage = "Demonstrate CLI usage"


    app.Commands = []cli.Command{

        {

            Name:    "one",

            Usage:   "first thing",

            Flags: []cli.Flag{

                cli.StringFlag{

                    Name:  "test",

                    Value: "foobar",

                    Usage: "something cool",

                },

            },

            Action: func(c *cli.Context) {

                fmt.Println("completed task", c.Command.Name, " with args ", c.Args())

                if (c.String("test") != "foobar") {

                    fmt.Println("Where'd foobar go?")

                }

            },

        },

        {

            Name:    "two",

            Usage:   "second thing",

            Flags: []cli.Flag{

                cli.StringFlag{

                    Name:  "test",

                    Value: "foobar",

                    Usage: "something cool",

                },

            },

            Action: func(c *cli.Context) {

                fmt.Println("completed task", c.Command.Name, " with args ", c.Args())

                fmt.Println("Testing value:", c.String("test"))

                if (c.String("test") != "foobar") {

                    fmt.Println("Where'd foobar go?")

                }

            },

        },

    }

    app.Run(os.Args)

}

快速示例:

無旗

$ ./sandbox two foo bar hello world

completed task two  with args  [foo bar hello world]

Testing value: foobar

帶旗

$ ./sandbox two foo bar hello world --test "see"

completed task two  with args  [foo bar hello world]

Testing value: see

Where'd foobar go?


查看完整回答
反對 回復 2021-11-29
  • 2 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號