[关闭]
@aloxc 2019-04-11T10:25:38.000000Z 字数 2869 阅读 388

go解析命令行参数方法

golang


1、通过os.Args来获取

  1. var help = func () {
  2. fmt.Println("Usage for calc tool.")
  3. fmt.Println("====================================================")
  4. fmt.Println("add 1 2, return 3")
  5. fmt.Println("sub 1 2, return -1")
  6. fmt.Println("mul 1 2, return 2")
  7. fmt.Println("sqrt 2, return 1.4142135623730951")
  8. }
  9. func CalcByOs() error {
  10. args := os.Args
  11. if len(args) < 3 || args == nil {
  12. help()
  13. return nil
  14. }
  15. operate := args[1]
  16. switch operate {
  17. case "add":{
  18. rt := 0
  19. number_one, err1 := strconv.Atoi(args[2])
  20. number_two, err2 := strconv.Atoi(args[3])
  21. if err1 == nil && err2 == nil {
  22. rt = number_one + number_two
  23. fmt.Println("Result ", rt)
  24. }
  25. }
  26. case "sub":
  27. {
  28. rt := 0
  29. number_one, err1 := strconv.Atoi(args[2])
  30. number_two, err2 := strconv.Atoi(args[3])
  31. if err1 == nil && err2 == nil {
  32. rt += number_one - number_two
  33. fmt.Println("Result ", rt)
  34. }
  35. }
  36. case "mul":
  37. {
  38. rt := 1
  39. number_one, err1 := strconv.Atoi(args[2])
  40. number_two, err2 := strconv.Atoi(args[3])
  41. if err1 == nil && err2 == nil {
  42. rt = number_one * number_two
  43. fmt.Println("Result ", rt)
  44. }
  45. }
  46. case "sqrt":
  47. {
  48. rt := float64(0)
  49. if len(args) != 3 {
  50. fmt.Println("Usage: sqrt 2, return 1.4142135623730951")
  51. return nil
  52. }
  53. number_one, err := strconv.ParseFloat(args[2], 64)
  54. if err == nil {
  55. rt = math.Sqrt(number_one)
  56. fmt.Println("Result ", rt)
  57. }
  58. }
  59. default:
  60. help()
  61. }
  62. return nil
  63. }

编译后执行

  1. ./calc add 1 2
  2. Result 3
  3. ====================
  4. ./calc sub 1 2
  5. Result -1
  6. ====================
  7. ./calc mul 10 20
  8. Result 200
  9. ===================
  10. ./calc sqrt 2
  11. Result 1.4142135623730951

2、使用flag

flag 包比 os 读取参数更方便。可以自定义传入的参数的类型:比如字符串,整型,浮点型,默认参数设置等
基本用法

  1. var operate string
  2. flag.StringVar(&operate,"o", "add", "operation for calc")
  3. # 解释
  4. 绑定 operate 变量, name="o", value="add" , usage="operation for calc"
  5. 也可以这样定义为指针变量
  6. var operate := flag.String("o", "add", "operation for calc")
  7. 同时还可以自定义 flag 类型
  8. 所有变量注册之后,调用 flag.Parse() 来解析命令行参数, 如果是绑定变量的方式,直接使用变量进行操作,
  9. 如果使用指针变量型,需要 *operate 这样使用。
  10. flag.Args() 表示接收的所有命令行参数集, 也是一个切片
  11. for index, value := range flag.Args {
  12. fmt.Println(index, value)
  13. }

示例程序

  1. func CalcByFlag() error {
  2. var operation string
  3. var numberone float64
  4. var numbertwo float64
  5. flag.StringVar(&operation, "o", "add", "operation for this tool")
  6. flag.Float64Var(&numberone, "n1", 0, "The first number")
  7. flag.Float64Var(&numbertwo, "n2", 0, "The second number")
  8. flag.Parse()
  9. fmt.Println(numberone, numbertwo)
  10. if operation == "add" {
  11. rt := numberone + numbertwo
  12. fmt.Println("Result ", rt)
  13. } else if operation == "sub" {
  14. rt := numberone - numbertwo
  15. fmt.Println("Result ", rt)
  16. } else if operation == "mul" {
  17. rt := numberone * numbertwo
  18. fmt.Println("Result ", rt)
  19. } else if operation == "sqrt" {
  20. rt := math.Sqrt(numberone)
  21. fmt.Println("Result ", rt)
  22. } else {
  23. help()
  24. }
  25. return nil
  26. }
  27. 最后的结果效果如下:
  28. ./calc -o add -n1 1 -n2 2
  29. Result 3
  30. =============================
  31. ./calc -o sub -n1 2 -n2 3
  32. Result -1
  33. ============================
  34. ./calc -o mul -n1 10 -n2 20
  35. Result 200
  36. ===========================
  37. ./calc -o sqrt -n1 2
  38. Result 1.4142135623730951

3、还是使用flag

  1. const (
  2. usage = `
  3. add --one ONE --two TWO "加法"
  4. `
  5. add = "add"
  6. )
  7. func main() {
  8. addCmd := flag.NewFlagSet(add, flag.ExitOnError)
  9. one := addCmd.Float64("one", 0, "one")
  10. two := addCmd.Float64("two", 0, "two")
  11. switch os.Args[1] {
  12. case add:
  13. err := addCmd.Parse(os.Args[2:])
  14. if err == nil{
  15. fmt.Println(err)
  16. }
  17. if addCmd.Parsed() {
  18. rt := *one + *two
  19. fmt.Println("Result ", rt)
  20. }
  21. }
  22. }
  23. 运行
  24. go run main2.go add --one 123 --two 321
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注