package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("os.Args")
}
os可以通过变量Args
来获取命令参数,os.Args
返回一个字符串数组。其中第一个参数就是执行文件的名字。
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "golang", "the name")
var year int
flag.IntVar(&year, "year", 2009, "the year")
flag.Parse()
fmt.Println("name:", *name)
fmt.Println("year:", year)
}
执行go run test.go,会得到
name: golang
year: 2009
当执行go run test.go -name=“benben” -year=2015。将会输出
name: benben
year: 2015
1、flag.String(name string, value string, usage string)
这个方法用来定义命令行获取的参数名称,默认值。方法会返回一个字符串变量的地址。这个地址中存储了flag参数的值。
func String(name string, value string, usage string) *string {
return CommandLine.String(name, value, usage)
}
func (f *FlagSet) String(name string, value string, usage string) *string {
p := new(string)
f.StringVar(p, name, value, usage)
return p
}
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
f.Var(newStringValue(value, p), name, usage)
}
func (f *FlagSet) Var(value Value, name string, usage string) {
// Remember the default value as a string; it won't change.
flag := &Flag{name, usage, value, value.String()}
_, alreadythere := f.formal[name]
if alreadythere {
var msg string
if f.name == "" {
msg = fmt.Sprintf("flag redefined: %s", name)
} else {
msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
}
fmt.Fprintln(f.Output(), msg)
panic(msg) // Happens only if flags are declared with identical names
}
if f.formal == nil {
f.formal = make(map[string]*Flag)
}
f.formal[name] = flag
}
2、flag.StringVar(p *string, name string, value string, usage string)
这个方法和String类似,也用来定义命令行获取的参数名称以及默认值。只不过这个方法中没有创建新的字符串指针来存储获取的字符串变量,而是用传进来的参数。
func StringVar(p *string, name string, value string, usage string) {
CommandLine.Var(new StringValue(value, p), name, usage)
}
func (f *FlagSet) Var(value Value, name string, usage string) {
// Remember the default value as a string; it won't change.
flag := &Flag{name, usage, value, value.String()}
_, alreadythere := f.formal[name]
if alreadythere {
var msg string
if f.name == "" {
msg = fmt.Sprintf("flag redefined: %s", name)
} else {
msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
}
fmt.Fprintln(f.Output(), msg)
panic(msg) // Happens only if flags are declared with identical names
}
if f.formal == nil {
f.formal = make(map[string]*Flag)
}
f.formal[name] = flag
}
3、flag.Parse()
这个方法会解析命令行参数,从os.Args[1:]
开始。这个函数必须在所有的flag都定义好之后,程序获取flag之前调用。
func Parse() {
CommandLine.Parse(os.Args[1:])
}