如何在Go中获取命令行参数而不使用“flags”包?

huangapple go评论104阅读模式
英文:

How do I get the command line arguments in Go without the "flags" package?

问题

我正在尝试为Go编写一个GNU风格的命令行解析器,因为flags包尚未处理所有这些情况:

program -aAtGc --long-option-1 argument-to-1 --long-option-2 -- real-argument

显然,我不想使用flags包,因为我正试图替换它。有其他方法可以获取命令行吗?

英文:

I'm trying to write a GNU-style command-line parser for Go, since the flags package doesn't handle all these yet:

program -aAtGc --long-option-1 argument-to-1 --long-option-2 -- real-argument

Obviously, I don't want to use the flags package, since I'm trying to replace it. Is there any other way to get to the command line?

答案1

得分: 45

不要紧。

package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args
    fmt.Printf("%d\n", len(args))

    for i := 0; i<len(args); i++ {
        fmt.Printf("%s\n", args[i])
    }
}

文档非常不完整。

英文:

Nevermind.

package main

import (
    &quot;fmt&quot;
    &quot;os&quot;
)

func main() {
    args := os.Args
    fmt.Printf(&quot;%d\n&quot;, len(args))

    for i := 0; i&lt;len(args); i++ {
 	    fmt.Printf(&quot;%s\n&quot;, args[i])
    }
}

The documentation is quite incomplete, though.

答案2

得分: 1

os.Args的第一个参数是go文件的名称,所以要获取命令行参数,你应该这样做:

package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args[1:]

    for i := 0; i<len(args); i++ {
        fmt.Println(args[i])
    }
}
英文:

The first argument of os.Args is the name of the go file, so to get only the command line arguments, you should do something like this

package main

import (
    &quot;fmt&quot;
    &quot;os&quot;
)

func main() {
    args := os.Args[1:]

    for i := 0; i&lt;len(args); i++ {
        fmt.Println(args[i])
    }
}

huangapple
  • 本文由 发表于 2009年11月11日 23:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/1715761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定