1. flag常用函数

无论是c语言还是golang语言或是其他语言,启动应用程序时都可以带一些参数,然后系统根据传入的参数进行特点的工作。如:./main -mode online -model bert_ch. 在Go中可以方便地使用flag模块进行命令行参数解析。


  1. // 解析字符串
  2. type string string
  3. func String(name string, value string, usage string) *string
  4. // 解析整数变量
  5. type int int
  6. func Int(name string, value int, usage string) *int
  7. // 解析bool变量
  8. type bool bool
  9. func Bool(name string, value bool, usage string) *bool
  10. type float64 float64
  11. func Float64(name string, value float64, usage string) *float64
  12. type int64 int64
  13. func Int64(name string, value int64, usage string) *int64
  14. // 解析使得参数生效
  15. func Parse()
  16. // 给指定的参数设置值
  17. func Set(name, value string) error
  18. // Flag结构体
  19. type Flag struct {
  20. Name string // name as it appears on command line
  21. Usage string // help message
  22. Value Value // value as set
  23. DefValue string // default value (as text); for usage message
  24. }
2. 案例测试

  1. package main
  2. import (
  3. " flag"
  4. " fmt"
  5. )
  6. func main() {
  7. mode := flag. String( "mode", "test", "test environment")
  8. model := flag. String( "model", "bert_ch", "select_embedding_model")
  9. re_train := flag. Bool( "retrain", false, "retrain bert or not")
  10. doc_num := flag. Int( "docnum", 20, "session_for_RS")
  11. flag. Parse()
  12. fmt. Println( "mode:", *mode)
  13. fmt. Println( "model:", *model)
  14. fmt. Println( "retrain:", *re_train)
  15. fmt. Println( "docnum:", *doc_num)
  16. }

测试结果:


  1. go run main. go -mode online -model bert_ch_large -retrain false -docnum 50
  2. output=
  3. mode: online
  4. model: bert_ch_large
  5. retrain: false
  6. docnum: 50