如何访问传递给 Go 程序的命令行参数?

如何访问 Go 中的命令行参数? 它们不作为参数传递给 main

一个完整的程序(可能是通过链接多个包创建的)必须有一个名为 main 的包和一个函数

func main() { ... }

Main ()函数不接受任何参数,也不返回任何值。

66733 次浏览

命令行参数可以在 os.Args中找到。但在大多数情况下,包 flag更好,因为它为您解析参数。

可以使用 os.Args变量访问命令行参数,

package main


import (
"fmt"
"os"
)


func main() {
fmt.Println(len(os.Args), os.Args)
}

您还可以使用 旗帜包裹,它实现命令行标志解析。

Peter 的回答正是你需要的如果你只是想要一个参数列表的话。

但是,如果您正在寻找与 UNIX 上类似的功能,那么可以使用 Docopt开始执行。你可以试试 给你

Docopt 将返回 JSON,然后您就可以对其进行全面处理。

Flag 是一个很好的包。

package main


// Go provides a `flag` package supporting basic
// command-line flag parsing. We'll use this package to
// implement our example command-line program.
import "flag"
import "fmt"


func main() {


// Basic flag declarations are available for string,
// integer, and boolean options. Here we declare a
// string flag `word` with a default value `"foo"`
// and a short description. This `flag.String` function
// returns a string pointer (not a string value);
// we'll see how to use this pointer below.
wordPtr := flag.String("word", "foo", "a string")


// This declares `numb` and `fork` flags, using a
// similar approach to the `word` flag.
numbPtr := flag.Int("numb", 42, "an int")
boolPtr := flag.Bool("fork", false, "a bool")


// It's also possible to declare an option that uses an
// existing var declared elsewhere in the program.
// Note that we need to pass in a pointer to the flag
// declaration function.
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")


// Once all flags are declared, call `flag.Parse()`
// to execute the command-line parsing.
flag.Parse()


// Here we'll just dump out the parsed options and
// any trailing positional arguments. Note that we
// need to dereference the pointers with e.g. `*wordPtr`
// to get the actual option values.
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *boolPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}

快速回答:

package main


import ("fmt"
"os"
)


func main() {
argsWithProg := os.Args
argsWithoutProg := os.Args[1:]
arg := os.Args[3]
fmt.Println(argsWithProg)
fmt.Println(argsWithoutProg)
fmt.Println(arg)
}

Test: $ go run test.go 1 2 3 4 5

Out:

[/tmp/go-build162373819/command-line-arguments/_obj/exe/modbus 1 2 3 4 5]
[1 2 3 4 5]
3

注意 : os.Args提供对原始命令行参数的访问。请注意,这个切片中的第一个值是程序的路径, os.Args[1:]保存程序的参数。 参考文献

例如,你可以使用 Golang 的旗帜包,

package main


import (
"flag"
"fmt"
)


func main() {


wordPtr := flag.String("word", "default value", "a string for description")
flag.Parse()
fmt.Println("word:", *wordPtr)


}

打电话给 Cli

 go run main.go -word=hello
 

 

output

word: hello