如何使用 boost::p rogram_options 解析本身包含开关的命令行参数

How can I parse command line arguments that themselves contain switches using boost::program_options?

本文关键字:包含 开关 参数 命令行 boost 何使用 rogram options      更新时间:2023-10-16

我正在用C++编写一个程序,它是一些基准测试的包装器,开头包含一些设置代码,最后包含analisys代码。

我想并行运行最多两个基准测试。 这些的原始命令行是:

/path0/benchmark0 -switch0 -switch1 -switch2
/path1/benchmark1 -arg0 -arg1 -arg2 -arg4

我想把它们放在我的包装器的命令行上:

wrapper -setup_arg0 -setup_arg1 -analysis_arg0 --command0 /path0/benchmark0 -switch0 -switch1 -switch2 --command1 /path1/benchmark1 -arg0 -arg1 -arg2 -arg4

我想得到两个std::vector<std::string>command0command1各一个,包含原始命令行。 这就是我的做法(使用 boost::program_options):

("command0", po::value<std::vector< std::string> >(&command0)->multitoken(), "command line for thread 0")
("command1", po::value<std::vector< std::string> >(&command1)->multitoken(), "command line for thread 1")

这基本上有效。 但是,如果基准测试的参数以-开头(就像我见过的大多数程序上的大多数开关一样),program_options会尝试将它们解析为包装器开关的一部分,因为它不知道它们应该在 command0command1 下分组在一起。

program_options支持吗? 如果是这样,如何?


例:

在我工作的地方,有一个约定可以通过像这样"终止"多令牌来执行此操作:

wrapper <snip> --command0 /path0/benchmark0 -switch0 -switch1 -switch2 -command0- 

(在此示例中,我以 -command0- 终止了--command0

我怎样才能program_options这样处理它?

我认为最好将

command0command1的值作为单个字符串。 例如,

wrapper --command0 "/path0/benchmark0 ..." --command1 "/path1/benchmark1 ..."

是的,对于您来说,还有更多的工作要做,因为您必须wordexp各自的命令字符串(除非您已经将这些字符串直接传递给 shell ;-)),但它更清楚地区分了包装器和

调用命令的内容。