无论是c语言还是golang语言或是其他语言,启动应用程序时都可以带一些参数,然后系统根据传入的参数进行特点的工作。如:./main -mode online -model bert_ch. 在Go中可以方便地使用flag模块进行命令行参数解析。
-
// 解析字符串
-
type string string
-
func String(name string, value string, usage string) *string
-
-
// 解析整数变量
-
type int int
-
func Int(name string, value int, usage string) *int
-
-
// 解析bool变量
-
type bool bool
-
func Bool(name string, value bool, usage string) *bool
-
-
type float64 float64
-
func Float64(name string, value float64, usage string) *float64
-
-
type int64 int64
-
func Int64(name string, value int64, usage string) *int64
-
-
// 解析使得参数生效
-
func Parse()
-
-
// 给指定的参数设置值
-
func Set(name, value string) error
-
-
// Flag结构体
-
type Flag struct {
-
Name
string
// name as it appears on command line
-
Usage
string
// help message
-
Value Value
// value as set
-
DefValue
string
// default value (as text); for usage message
-
}
2. 案例测试
-
package
main
-
-
import (
-
"
flag"
-
"
fmt"
-
)
-
-
func
main() {
-
mode := flag.
String(
"mode",
"test",
"test environment")
-
model := flag.
String(
"model",
"bert_ch",
"select_embedding_model")
-
re_train := flag.
Bool(
"retrain", false,
"retrain bert or not")
-
doc_num := flag.
Int(
"docnum", 20,
"session_for_RS")
-
-
flag.
Parse()
-
-
fmt.
Println(
"mode:", *mode)
-
fmt.
Println(
"model:", *model)
-
fmt.
Println(
"retrain:", *re_train)
-
fmt.
Println(
"docnum:", *doc_num)
-
}
测试结果:
-
go run main.
go -mode online -model bert_ch_large -retrain
false -docnum
50
-
-
output=
-
mode: online
-
model: bert_ch_large
-
retrain:
false
-
docnum:
50