英文:
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 (
"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])
}
}
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 (
"fmt"
"os"
)
func main() {
args := os.Args[1:]
for i := 0; i<len(args); i++ {
fmt.Println(args[i])
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论