如何在Go中访问带有Cli的命令数组?

时间:2015-12-22 05:13:31

标签: go

目前正在使用Codegangsta's Cli Library。我像这样运行一个命令:

myGoProgram arg1 arg2 arg3 --flag1 flag1arg 

正在运行

app.Action = func(c *cli.Context) {
        fmt.Println("Context: ", c.Args())
}

返回:[arg1 arg2 arg3 --flag1 flag1arg]c.Args()'s return type

如何访问arg1arg2arg3,而不是--flag1flag1arg?我是否必须遍历此数组?

2 个答案:

答案 0 :(得分:0)

好的,我所做的就是创建两个相同内容的数组,并相应地删除元素,以创建仅包含原始命令的数组。

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
}

答案 1 :(得分:0)

我认为你可能没有正确定义你的旗帜,看看我做的这个例子:

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?