在Caffe源码中,命令行参数的解析都是用gflags的库。在安装Caffe依赖包的时候就有libgflags-dev这个包。gflags是google开发的开源命令行解析库,使用C++开发,用起来比getopt更方便。
以 tools/caffe.cpp 为例分析gflags使用方法
在tools/caffe.cpp中首先包含了gflags的头文件
#include <gflags/gflags.h>
命令行参数传递
接下来定义了一些需要从命令行传递参数的变量
DEFINE_string(gpu, "",
"Optional; run in GPU mode on given device IDs separated by ','."
"Use '-gpu all' to run on all available GPUs. The effective training "
"batch size is multiplied by the number of devices.");
DEFINE_string(solver, "",
"The solver definition protocol buffer text file.");
DEFINE_string(model, "",
"The model definition protocol buffer text file.");
DEFINE_string(phase, "",
"Optional; network phase (TRAIN or TEST). Only used for 'time'.");
DEFINE_int32(level, 0,
"Optional; network level.");
......
这些参数使用gflags提供的宏:DEFINE_xxx(变量名,默认值,help_string)。这些变量需要在全局范围内定义。变量支持以下类型:
定义 | 类型 |
---|---|
DEFINE_bool | 布尔型 |
DEFINE_int32 | 32位整形 |
DEFINE_int64 | 64位整形 |
DEFINE_uint64 | 64位无符号整形 |
DEFINE_double | double型 |
DEFINE_string | C++中string类型 |
在main函数中调用的GlobalInit()函数中调用了ParseCommandLineFlags()
// Google flags.
::gflags::ParseCommandLineFlags(pargc, pargv, true);
这个函数的作用就是解析命令行参数。
pargc,pargv为命令行传递的参数个数和参数表,第三个参数作用为:
值 | 作用 |
---|---|
true | 函数处理完成后,argv中只保留argv[0],argc会被设置为1。 |
false | argv和argc会被保留,但是注意函数会调整argv中的顺序。 |
执行完这参数后,就可以用FLAGS_xxx访问变量了。
例如caffe.cpp中, FLAGS_solve表示命令行参数传递的模型文件,FLAGS_weights表示令行参数传递的权值文件
// Train / Finetune a model.
int train() {
CHECK_GT(FLAGS_solver.size(), 0) << "Need a solver definition to train.";
CHECK(!FLAGS_snapshot.size() || !FLAGS_weights.size())
<< "Give a snapshot to resume training or weights to finetune "
"but not both.";
帮助信息
gflags::SetUsageMessage函数用于设置命令行帮助信息。
// Usage message.
gflags::SetUsageMessage("command line brew\n"
"usage: caffe <command> <args>\n\n"
"commands:\n"
" train train or finetune a model\n"
" test score a model\n"
" device_query show GPU diagnostic information\n"
" time benchmark model execution time");
设置帮助信息后,当参数错误或加 -help选项是可以打印帮助信息
$ ./build/tools/caffe
caffe: command line brew
usage: caffe <command> <args>
commands:
train train or finetune a model
test score a model
device_query show GPU diagnostic information
time benchmark model execution time
...
版本信息
gflags::SetVersionString用于设置版本信息
// Set version
gflags::SetVersionString(AS_STRING(CAFFE_VERSION));
这里的CAFFE_VERSION是在Makefile中定义的
当命令行参数加 -version 时会打印版本信息
$ ./build/tools/caffe -version
caffe version 1.0.0-rc3