Example of parsing command-line options

我们解释下这些选项是如何被 C++ 处理的,下面是 gmm-align.cc中的部分代码(为了表达更清晰,略微改动了下):

int main(int argc, char argv[]) { try { // try-catch block is standard and relates to handling of errors. using namespace kaldi; const char usage = "Align features given [GMM-based] models.\n" "Usage: align-gmm [options] tree-in model-in lexicon-fst-in feature-rspecifier " "transcriptions-rspecifier alignments-wspecifier\n"; // Initialize the ParseOptions object with the usage string. ParseOptions po(usage); // Declare options and set default values. bool binary = false; BaseFloat beam = 200.0; // Below is a structure containing options; its initializer sets defaults. TrainingGraphCompilerOptions gopts; // Register the options with the ParseOptions object. po.Register("binary", &binary, "Write output in binary mode"); po.Register("beam", &beam, "Decoding beam"); gopts.Register(&po); // The command-line options get parsed here. po.Read(argc, argv); // Check that there are a valid number of positional arguments. if(po.NumArgs() != 6) { po.PrintUsage(); exit(1); } // The positional arguments get read here (they can only be obtained // from ParseOptions as strings). std::string tree_in_filename = po.GetArg(1); ... std::string alignment_wspecifier = po.GetArg(6); ... } catch(const std::exception& e) { std::cerr << e.what(); return -1; } }

读上面的代码基本就明白它的功能。在通常的 Kaldi 程序中,处理流程是这样的:

  • 用包含使用说明的字符串初始化 ParseOptions 对象
  • 声明并给出可选参数(选项结构(options structure))的初始值
  • 用 ParseOptions 对象注册命令行选项(选项结构有它们自己的注册函数,执行同样的功能)
  • 执行 “po.Read(argc, argv);”[如果存在无效选项,此处会退出程序]
  • 检查 po.NumArgs() 在有效范围内
  • 利用 po.GetArg(1) 等获取位置参数;对可能超出有效数目范围的可选位置参数来说,可用 po.GetOptArg(n)来获取第n个参数,如果n超出范围则返回空字符串

一般来说,在 Kaldi 程序中写一个新命令行时,最简单的方法就是拷贝一个现成的然后修改它。

results matching ""

    No results matching ""