【问题标题】:How can I parse command line arguments that themselves contain switches using boost::program_options?如何使用 boost::program_options 解析本身包含开关的命令行参数?
【发布时间】:2012-04-19 19:59:26
【问题描述】:

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

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

/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>s,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这样处理?

【问题讨论】:

    标签: c++ boost-program-options


    【解决方案1】:

    我认为最好将command0command1 的值作为单个字符串。例如,

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

    是的,还有更多工作要做,因为您必须 wordexp 各自的命令字符串(除非您已经将这些字符串直接传递给 shell ;-)),但它更清楚地分离出什么是包装器以及调用的命令是什么。

    【讨论】:

    • 我需要将命令传递给exec。有没有一种好方法可以将这样的字符串传递给exec,或者我需要将它分解成一个字符串数组? wordexp 是这样做的吗?
    • 如果您的命令字符串是可信的(即您不必担心攻击者等),只需使用execl("/bin/sh", "/bin/sh", "-c", cmd, static_cast&lt;char*&gt;(0))。如果它不受信任,那么可以,使用wordexp 扩展。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2011-02-02
    • 2011-05-17
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多