Skip to content

命令行解析

使用 os.Args 获取简单参数

package main

import (
    "fmt"
    "os"
)

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


// 输出
MacintoshdeMacBook-Pro-139:terminal elasticnotes$ go run args.go 1 2 3 4 5
[/var/folders/7w/0j7vff4j1kz5_g43cf_vqlg00000gp/T/go-build189031535/b001/exe/args 1 2 3 4 5]

使用 flag 获取复杂参数

package main

import (
    "flag"
    "fmt"
)

func main() {
    methodPtr := flag.String("method", "default", "method of sample")

    valuePtr := flag.Int("value", -1, "value of sample")

    flag.Parse()

    fmt.Println(*methodPtr, *valuePtr)
}


// 输出
MacintoshdeMacBook-Pro-139:terminal elasticnotes$ go run flag.go 
default -1
MacintoshdeMacBook-Pro-139:terminal elasticnotes$ go run flag.go -method 你好
你好 -1