Go 语言文件操作:从命令行读取参数
1 使用os包读取命令行参数
os包有一个全局变量Args,是[]string类型,第一个元素是程序名
示例代码
func main() {
for i, v := range os.Args {
fmt.Printf("这是第%d个参数:%s\n", i, v)
}
}
运行结果
nothin:~/GoPractice/flags$ go build -o flag
nothin:~/GoPractice/flags$ ./flag p1 p2 p3
这是第0个参数:./flag
这是第1个参数:p1
这是第2个参数:p2
这是第3个参数:p3
2 使用flag包
flag包就比os.Args更加灵活,不过其也有一些限制,比如说官方不推荐在init函数中调用flag.Parse,这样会使得不同包之间的flag出现问题
示例代码
func main() {
str := flag.String("s", "hello world", "test string")
num := flag.Int("n", 0, "test number")
bol := flag.Bool("b", false, "test bool")
//在使用flag包定义的参数之前,一定要先运行Parse
flag.Parse()
fmt.Println("string paramter:", *str)
fmt.Println("number parameter:", *num)
fmt.Println("bool parameter", *bol)
}
运行结果
nothin:~/GoPractice/flags$ ./flag2 -s="hello world" -n=123 -b=true
string paramter: hello world
number parameter: 123
bool parameter true
#这里加一个-d,因为程序内部没有定义d,所以程序会出错并抛出预先写好的usage
nothin:~/GoPractice/flags$ ./flag2 -s="hello world" -n=123 -b=true -d
flag provided but not defined: -d
Usage of ./flag2:
-b test bool
-n int
test number
-s string
test string (default "hello world")
推荐文章: